GithubHelp home page GithubHelp logo

isoos / elastic_client Goto Github PK

View Code? Open in Web Editor NEW
44.0 44.0 28.0 88 KB

Dart bindings for ElasticSearch HTTP API.

Home Page: https://pub.dartlang.org/packages/elastic_client

License: BSD 3-Clause "New" or "Revised" License

Dart 100.00%

elastic_client's People

Contributors

apinprastya avatar asayamakk avatar cronos87 avatar dopecoder avatar fabiocarneiro avatar fpause avatar gvisniuc avatar isoos avatar jodinathan avatar olachris avatar saadardati avatar sidrao2006 avatar sota1235 avatar swdyh avatar uttufy avatar vi-cs avatar wapa5pow avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

elastic_client's Issues

ssl certificate

good day everyone, I'm doing end of study project
is there a way to authenticate elastic_client using self signed certificate (pem)

example does not work

Same as the example
final rs = await client.search( 'my_index', 'my_type', elastic.Query.term('some', ['data']));

and the traceback
Unhandled exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'int' in type cast #0 Client.search (package:elastic_client/src/elastic_client_impl.dart:123:46) <asynchronous suspension> #1 main (package:dartcli/dartcli.dart:12:27) <asynchronous suspension> #2 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:300:19) #3 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:171:12)

mergeHeader PR?

Just stumbled upon the merge header error and forked the repo to fix it, however, the code is already fixed.
Maybe it is missing a PR?

nested aggs?

I am trying to use nested aggs but the result is not parsed.

I've dug the Aggregation constructor and it doesn't parse inner aggregations within an aggregation.

I am not a elasticsearch expert, so I don't know if I am doing something wrong.

Here is the code:

final rs1 = await searchDbClient.search('watched', '', null,
        limit: 0,
        aggregations: {
          'calc': {
            'filter': {
              'term': {'eventId': '5eb1802b8ef23f8605ef11fd'}
            },
            'aggs': {
              'visitors': {
                'terms': {'field': 'visitorId.keyword'},
                'aggs': {
                  'first_event': {
                    'top_hits': {
                      'sort': [
                        {
                          'date': {'order': 'desc'}
                        }
                      ],
                      'from': 0,
                      'size': 1
                    }
                  }
                }
              }
            }
          }
        },
        source: true);
    print('calc!: ');
    rs1.aggregations.forEach((k, vv) {
      print(k);
      print(vv.toMap());
    });

it only prints

calc
{name: calc}

The result is ok when executed within kibana's console:

{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : 278,
    "max_score" : 0.0,
    "hits" : [ ]
  },
  "aggregations" : {
    "calc" : {
      "doc_count" : 278,
      "visitors" : {
        "doc_count_error_upper_bound" : 0,
        "sum_other_doc_count" : 0,
        "buckets" : [
          {
            "key" : "5eb6d70a2b5550f5a3fcb9c3",
            "doc_count" : 278,
            "first_event" : {
              "hits" : {
                "total" : 278,
                "max_score" : null,
                "hits" : [
                  {
                    "_index" : "watched",
                    "_type" : "_doc",
                    "_id" : "blhyAHIBF4DbsdYY9OUO",
                    "_score" : null,
                    "_source" : {
                      "eventId" : "5eb1802b8ef23f8605ef11fd",
                      "itemId" : "5eb86b8774ea3964d6ee0aee",
                      "questionId" : "5e895842fa09c4a0aa9a6dd5",
                      "visitorId" : "5eb6d70a2b5550f5a3fcb9c3",
                      "time" : null,
                      "index" : 4,
                      "date" : "2020-05-10T21:17:12.714295Z"
                    },
                    "sort" : [
                      1589145432714
                    ]
                  }
                ]
              }
            }
          }
        ]
      }
    }
  }
}

Need more examples to make post calls for a REST API?

Hi,

I understood the benefits of this package and really appreciate the work, but it would be great if there is a proper example for making POST calls to a rest API so that it would be easy to us to make a serachQuery format and make the needful, I have gone through several articles in which I could not understand how to format a searchQuery for the below json, any help would be great and thanks.

Here is my json body for a rest API call:

{
"size": 0,
"aggs": {
"sales_over_time": {
"date_histogram": {
"field": "createdon",
"calendar_interval": "hour"
},
"aggs":{
"revenuetype":{
"terms":{
"field":"revenuetype"
},
"aggs":{
"amount":{
"sum":{
"field":"amount"
}
}
}
}
}
}
}
}

'Client' isn't a function issue

image

[class Client, abstract class Client]
The name 'Client' is defined in the libraries 'package:elastic_client/src/elastic_client_impl.dart (via package:elastic_client/elastic_client.dart)' and 'package:http/src/client.dart (via package:http/http.dart)'.
Try using 'as prefix' for one of the import directives, or hiding the name from all but one of the imports.dartambiguous_import
'Client' isn't a function.
Try correcting the name to match an existing function, or define a method or function named 'Client'.dartinvocation_of_non_function

Line taken from: https://github.com/isoos/elastic_client/blob/master/example/example.dart

In my pubspec.yaml I have installed:
elastic_client: ^0.3.1

some help would be very appreciated!

Exception: Failed to search {terms: {companies.companyName: [data]}}

Hello,
I was attempting to use your plug in but I cant seem to get it to work using your example as a guide.

var client = new elastic.Client(ConsoleHttpTransport(Uri.parse('http://35.198.171.246//elasticsearch/'), basicAuth: BasicAuth('user','******')) );

Then I built a test function

search()
async {
final rs2 = await client.search(

  'companies',

  'companies',

  elastic.Query.term('companies.companyName', ['data']),

  source: ['companies.companyName', 'companyName'],

  //sort: [{ "name" : "asc" }, { "name.keyword" : "asc" }]

);
  print(rs2.toMap());

}

Then I am getting the following Error

E/flutter ( 4289): Exception: Failed to search {terms: {companies.companyName: [data]}}
E/flutter ( 4289): #0 Client.search
package:elastic_client/src/elastic_client_impl.dart:127
E/flutter ( 4289):
E/flutter ( 4289): #1 _ClientSearchState.search
package:GreenSFA/agentPages/searchClient.dart:389
E/flutter ( 4289):
E/flutter ( 4289): #2 _ClientSearchState.build

SocketException

Hi I'm getting this error : "SocketException (SocketException: OS Error: Connection refused, errno = 111, address = localhost, port = 53392)."

this is the code I wrote :

Future <List> fetchElaProperty() async {
String url = 'http://localhost:9200/';
final transport =ConsoleHttpTransport(Uri.parse(url));
final client = elastic.Client(transport);
//in the code below is whre I get the error.
final response = await client.search(
'fproperty',
'_doc',
elastic.Query.term('purpose', ['venta']),
source: true
);
print(response.toMap());
}

Any idea how to use with auth?

Hey @isoos ,

I am using opendistro with elasticsearch, open distro basic auth is enabled.
To get the response successfully from the server we need to send the request in the following way: curl -XGET https://<IP Address>:9200 -u userid:password --insecure

You see additional parameters -u userid:password --insecure is always required to get a response.

any idea how can we do this here?

Null _score value causing issues with Flutter 3.13.4

Hi there,

I've recently upgraded flutter to 3.13.4 and began work on null safety.

In some cases, for example top_hits aggregations, the _score key is missing from the hits causing an error when casting the null value to double.

https://github.com/isoos/elastic_client/blob/master/lib/src/elastic_client_impl.dart#L147C15-L147C46

Fixed it for now with score: map['_score'] != null ? map['_score'] as double : 0.0, but there might be a better solution of course.

Unable to run multi nested Query

Unable to run a complicated query for example:

{
"suggest": {
"movie-suggest" : {
"prefix" : "captain america the",
"completion" : {
"field" : "name.completion"
}
}
}
}

Any idea how this can be achieved?

How to combine multiple query into one???

My user search
"the avenger infinity war"

so I need complex query in three part
Part 1: importance 1.5
phrase search : "the avenger infinity war"

PArt 2: importance 1.0
Word search "the" and "avenger" and "infinity" and "war"

PArt 3: importance 0.5
Fuzzy search
"the"~0.5 and
"avenger"~0.5 and
"infinity"~0.5 and
"war"~0.5

combining this search to one. well I am willing to contribute if you show me some way to build this, in string version i can made this, but don't know how to build in Map<dynamic, dynamic>

is there any way, just a small hint will also be much helpful.

even just a small reference of code how to combine multiple query into one would be helpful, and in response I am happy to share my final search query builder code. I did same with lucene.net desktop version with much more complex query, I am trying to do same here, and I am sure that this will help many other fellow programmers.

Please help from my question

Good morning. Thank you for creating the elastic_client package. I want to implement a list of 10 items, in order, from elasticsearch and attach them to the app list and display them to the user. How can I do this for this?? Please help me in this question.

I'm getting a platform exception when trying to use the client.search on the web

Hi, the client works great for my use case on a device but when I try and call search from the web I get the following error.

errors.dart:165 Uncaught (in promise) Error: Unsupported operation: Platform._version
    at Object.throw_ [as throw] (errors.dart:214)
    at Function._version (io_patch.dart:289)
    at Function.get version [as version] (platform_impl.dart:119)
    at get _version (platform.dart:74)
    at Function.desc.get [as _version] (operations.dart:781)
    at Function.get version [as version] (platform.dart:231)
    at Object._getHttpVersion (http_impl.dart:3374)
    at new _http._HttpClient.new (http_impl.dart:2157)
    at Function.new (http.dart:1556)
    at Function.new (console.dart:45)
    at new console_http_transport.ConsoleHttpTransport.new (console_http_transport.dart:10)
    at new elastic.Elastic.new (elastic.dart:13)
    at chat_screen._ChatScreenState.new.filteredStream (chat_screen.dart:81)
    at chat_screen.dart:66
    at chat_screen._ChatScreenState.new.setState (framework.dart:1236)
    at chat_screen._ChatScreenState.new.<anonymous> (chat_screen.dart:65)
    at Generator.next (<anonymous>)
    at runBody (async_patch.dart:84)
    at Object._async [as async] (async_patch.dart:123)
    at editable_text.EditableText.new.<anonymous> (chat_screen.dart:63)
    at editable_text.EditableTextState.new.[_formatAndSetValue] (editable_text.dart:1788)
    at editable_text.EditableTextState.new.updateEditingValue (editable_text.dart:1349)
    at text_input.TextInput.__._handleTextInputInvocation (text_input.dart:1121)
    at _handleTextInputInvocation.next (<anonymous>)
    at runBody (async_patch.dart:84)
    at Object._async [as async] (async_patch.dart:123)
    at text_input.TextInput.__.[_handleTextInputInvocation] (text_input.dart:1081)
    at OptionalMethodChannel._handleAsMethodCall (platform_channel.dart:430)
    at _handleAsMethodCall.next (<anonymous>)
    at runBody (async_patch.dart:84)
    at Object._async [as async] (async_patch.dart:123)
    at OptionalMethodChannel.[_handleAsMethodCall] (platform_channel.dart:427)
    at platform_channel.dart:383
    at handlePlatformMessage (binding.dart:265)
    at handlePlatformMessage.next (<anonymous>)
    at runBody (async_patch.dart:84)
    at Object._async [as async] (async_patch.dart:123)
    at _DefaultBinaryMessenger.handlePlatformMessage (binding.dart:256)
    at Object._invoke3 (window.dart:756)
    at _engine.EngineWindow.new.invokeOnPlatformMessage (window.dart:424)
    at _engine.TextEditingChannel.new.updateEditingState (text_editing.dart:1094)
    at _engine.GloballyPositionedTextEditingStrategy.new.<anonymous> (text_editing.dart:1280)
    at _engine.GloballyPositionedTextEditingStrategy.new.[_handleChange] (text_editing.dart:698)
    at Object._checkAndCall (operations.dart:324)
    at Object.dcall (operations.dart:329)
    at HTMLInputElement.<anonymous> (html_dart2js.dart:37175)

If helpful here is the code I'm using

class Elastic {
  static const URL =
      "URL";
  static const USERNAME = "USERNAME";
  static const PASSWORD = "PASSWORD";
  Transport transport;
  Client client;
  Elastic() {
    transport = ConsoleHttpTransport(Uri.parse(URL),
        basicAuth: BasicAuth(USERNAME, PASSWORD));
    client = elastic.Client(transport);
  }

  Future<List<MessageBubble>> search({
    String searchTerm,
    String senderEmail,
  }) async {
    List<MessageBubble> res;
    try {
      final SearchResult result = await client.search('messages', '_doc',
          elastic.Query.match('text', searchTerm, minimum: senderEmail),
          source: true);

      if (result.toMap()['totalCount'] == 0) {
        return [];
      } else {
        res = result
            .toMap()['hits']
            .map((e) => e['doc'])
            .map<MessageBubble>((e) => MessageBubble(
                text: e['text'],
                sender: e['sender'],
                isMe: senderEmail == e['sender']))
            .toList();
      }
    } catch (e) {
      print("this is a problem in web $e");
    }

    return res;
  }
}

Issues obtaining only suggestions

First problem:

There is no way to retrieve only suggestions since the 'query' field is mandatory. Unnecessary data is returned, consuming unnecessary network resources.

\elastic_client-0.3.15\lib\src\_client.dart at line 300


  final map = {
      if (source != null) '_source': source,
      if (fields != null) 'fields': fields,
      'query': query ?? Query.matchAll(),                            // hereeeeee
      if (offset != null) 'from': offset,
      if (limit != null) 'size': limit,
      if (suggest != null) 'suggest': suggest,
      if (sort != null) 'sort': sort,
      if (aggregations != null) 'aggregations': aggregations,
      if (highlight != null) 'highlight': highlight.toMap(),
      if (trackTotalHits != null) 'track_total_hits': trackTotalHits,
      if (size != null) 'size': size,
      if (minScore != null) 'min_score': minScore,
      if (knn != null) 'knn': knn,
    };

Second Issue:

The mapping with the response JSON does not match as illustrated below.

Elasticsearch Response Version: 8.11.4


{
    "took": 0,
    "timed_out": false,
    "_shards": {
      "total": 1,
      "successful": 1,
      "skipped": 0,
      "failed": 0
    },
    "hits": {
      "total": {
        "value": 0,
        "relation": "eq"
      },
      "max_score": null,
      "hits": []
    },
    "suggest": {
      "suggestion": [
        {
          "text": "123",
          "offset": 0,
          "length": 3,
          "options": [
            {
              "text": "123",
              "_index": "suggestions",
              "_id": "123",
              "_score": 30,
              "_source": {
                "name": "123",
                "suggest": {
                  "input": [
                    "123"
                  ],
                  "weight": 30
                }
              }
            }
          ]
        }
      ]
    }
  }

Mapping of the file \elastic_client-0.3.15\lib\src\_client.dart at line 331


return SuggestHitOption(
            m['text'] as String,
            m['score'] as double, // <--------hereee
            freq: (m['freq'] ?? -1) as int,
            highlighted: m['highlighted'] as String,
          );

Prefix Queries

Hello,

I have a question, using your plug in how can I make a prefix query "prefix": { "itemCode.keyword": "111"...

@mayankjanmejay: I've published 0.1.7 that should handle the hits.total.value response. Could you please open separate issues for the new ones? It is easier to track the separate threads and answer them accordingly.

Originally posted by @isoos in #10 (comment)

Add description

Can you add a description to the package so we know what it's for? I was about to share it, but there's no info to help the dev know what it is and how to use it

Filter Search

Sorry am i missing something? How do i do a filter query like this
GET /shirts/_search
{
"query": {
"bool": {
"filter": [
{ "term": { "color": "red" }},
{ "term": { "brand": "gucci" }}
]
}
},
"aggs": {
"models": {
"terms": { "field": "model" }
}
}
}

Query.bool doesn't support minimum_should_match

abstract class Query {

static Map bool({
dynamic must,
dynamic filter,
dynamic should,
dynamic mustNot,
})
{
return {
'bool': {
if (must != null) 'must': must,
if (filter != null) 'filter': filter,
if (should != null) 'should': should,
if (mustNot != null) 'mustNot': mustNot,
}
};
}

HighlightOptions need some help......

I am new to flutter, and Since last few days i am struggling with configuring HighlightOptions field in elastic_client,

can anyone help me HighlightOptions example,

thanks from me, you guyz did a great job, it helped me a lot to connect and search my flutter app to ES. just his HighlightOptions part I can't figure out, its quite complicated for me.

Change "_source" logic in Client.search() method

Hi, thanks for this Elasticsearch client!

I would like to be able to use source filtering as per https://www.elastic.co/guide/en/elasticsearch/reference/7.2/search-request-source-filtering.html.

This doesnt work at the moment because in the Client.search() method in elastic_client_impl.dart "_source" is always set as a bool. Elasticsearch allows this to be a boolean, a string or a list of strings (I need the latter).

To make this possible i would like to make the following changes:

  • Add a param 'source' with type dynamic to the search() method
  • if that has a value then use it as "_source"
  • if it does not have a value then set it to true or false based on the fetchSource param

(Note that the fetchSource param is only kept to ensure this is a backwards compatible change. If you are not concerned with keeping backwards compatibility then the change can simply be:

  • Rename fetchSource param to source, and change its type from bool to dynamic)

Would you accept a PR that makes those changes?:

Exception when searching using aggregation

First of all, thank you for creating an maintaining the project!

I started using flutter with elastic search yesterday and started using this package.

But when searching with an aggregation I unfortunately got an error in https://github.com/isoos/elastic_client/blob/master/lib/src/elastic_client_impl.dart in lines 130-134.

name = name;  
value = m['value'];  
values = m['values'] as Map;  
docCountErrorUpperBound = m['doc_count_error_upper_bound'] as int;  
sumOtherDocCount = m['sum_other_doc_count'] as int;  

My search query:

client.search(index: 'sensordata', type: '', aggregations: {
      'values': {
        'composite': {
          'sources': [
            {
              'value': {
                'terms': {'field': 'sensorname'}
              }
            }
          ]
        }
      }
    });

I looked up in the documentation https://pub.flutter-io.cn/documentation/elastic_client/latest/elastic_client/Aggregation-class.html and found that values for example should be of type Map? but is, as seen in the code block above of type Map.

After making the fields values, docCountErrorUpperBound and sumOtherDocCount nullable everything worked fine.

Can anybody confirm that problem?

Cannot get value from second field from search result

I can search for a document by one field and get results just fine, but how can I get the values from the other fields that specific document has?

My expected result:

ListTile(
   title: Text(foodName),
   subtitle: Text(brandName),
);

This is my working code (you're free to add it as a real-world-example using Elastic Cloud in this repo if you want):

import 'package:elastic_client/elastic_client.dart';
import 'package:flutter/material.dart';
import 'package:elastic_client/elastic_client.dart' as elastic;

class ElasticSearchDelegate extends SearchDelegate {

  @override
  List<Widget> buildActions(BuildContext context) {
    return [
      IconButton(
        icon: Icon(Icons.clear),
        onPressed: () async {
          query = '';
          await searchElasticServer(query);
        },
      ),
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
      icon: Icon(Icons.arrow_back),
      onPressed: () {
        close(context, null);
      },
    );
  }

  Future searchElasticServer(searchQuery) async {
    final transport = HttpTransport(
      url: 'ELASTIC_SEARCH_ENDPOINT_URL',
      authorization: basicAuthorization("ELASTIC_SEARCH_USERNAME", "ELASTIC_SEARCH_PASSWORD"));
    final client = elastic.Client(transport);

    List<String> foodsList = List();

    final searchResult = await client.search(
        index: 'foods', 
        type: '_doc', 
        query: elastic.Query.term('foodName', ['$searchQuery']),
        source: true);

    print("----------- Found ${searchResult.totalCount} $searchQuery ----------");

    for(final iter in searchResult.hits){
      Map<dynamic, dynamic> currDoc = iter.doc;

      print(currDoc);

      foodsList.add(
        currDoc['foodName'].toString(),
        );
    }

    await transport.close();

    if(searchResult.totalCount <= 0 )
      return null;
    else
      return foodsList;
  }

  @override
  Widget buildResults(BuildContext context) {
    return FutureBuilder(
      future: searchElasticServer(query),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        if (!snapshot.hasData) return Center(child: Text("No results"));

        return  _displayFoodResult(snapshot.data) ;
      },
    );
  }

  @override
  Widget buildSuggestions(BuildContext context) {

    return FutureBuilder(
      future: searchElasticServer(query),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        if (!snapshot.hasData) return Text("No results");

        return _displayFoodResult(snapshot.data) ;
      },
    );
  }


  Widget _displayFoodResult( List<String> foodList) {
    return ListView.builder(
      itemCount: foodList.length,
      itemBuilder: (BuildContext context, int index) {
        return ListTile(
          title: Text(foodList[index]),
        );
      }
    );
  }

}

Result on screen:
image

Debug Console result:
image

How is this project's status?

roadmaps ect.. + would like to join as contributor since i need to back fully functioning flutter web app with elasticsearch

XMLHttpRequest error when using in flutter web

When trying to use this package in flutter web I come across this error. XMLHttpRequest error. On ios and Android it works fine. Any Idea's how to fix this issue?

Error: XMLHttpRequest error.
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patch/core_patch.dart 910:28 get current
packages/http/src/browser_client.dart 69:22
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/zone.dart 1685:54 runUnary
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 159:18 handleValue
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 766:44 handleValueCallback
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 795:13 _propagateToListeners
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 592:7 [_complete]
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/stream_pipe.dart 61:11 _cancelAndValue
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/stream.dart 1288:7
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 334:14 _checkAndCall
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 339:39 dcall
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/html/dart2js/html_dart2js.dart 37301:58

at Object.createErrorWithStack (http://localhost/dart_sdk.js:5080:12)
at Function._throw (http://localhost/dart_sdk.js:20337:18)
at Function.throwWithStackTrace (http://localhost/dart_sdk.js:20334:18)
at async._AsyncCallbackEntry.new.callback (http://localhost/dart_sdk.js:40851:18)
at Object._microtaskLoop (http://localhost/dart_sdk.js:40708:13)
at _startMicrotaskLoop (http://localhost/dart_sdk.js:40714:13)
at http://localhost/dart_sdk.js:36191:9

Write example

Please write example on (elastic_client) DART from my python code.

q = {
  "query": {
    "multi_match": {
      "query":    "John*",
      "fields": "*"
    }
  }
}

res = es.search(index="kpmi_etalon_obj", body=q)
print("Got %d Hits:" % res['hits']['total']['value'])
for hit in res['hits']['hits']:
    print(hit['_source']['etalonId'])

Support for appsearch

Considering dart is primarily a mobile centric language due to its early adoption with flutter. I really think native app search methods should be high priority for this client.

Please correct me if I'm mistaken and this package already works with appsearch?

Phrase suggestion not working on DART elastic_client ?

Hi,

I am trying to get phrases suggestions on my Flutter app using client.search() from https://pub.dev/packages/elastic_client

Works fine on REST API :
`{
"suggest":{
"text": "Britih",
"content": {
"phrase": {
"field": "content",
"highlight": {
"pre_tag": "",
"post_tag": "
"
}
}
}
}

}`

However, when I replicate this request on dart/Flutter, I get the following error:
[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type 'Null' is not a subtype of type 'int' in type cast #0 Client.search.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:elastic_client/src/_client.dart:331:29) #1 MappedListIterable.elementAt (dart:_internal/iterable.dart:413:31) #2 ListIterator.moveNext (dart:_internal/iterable.dart:342:26)

It seems to me that in _client.dart, frequency is expected but elastic return none.

return SuggestHitOption(
            m['text'] as String,
            m['score'] as double,
            freq: m['freq'] as int, <== ligne 331
            highlighted: m['highlighted'] as String,
          );

how to map a match_phrase query?

If I run the following query in Kibana it works, but a need to implement it in flutter. Please, can you teach me how can I map a query.

POST /books/_search
{
    "query": {
        "match_phrase": {
            "name" : {
                "query" : "Roberts book",
                "slop": 50
            }
        }
    }
}

My data structure is:

      {
        "_index" : "books",
        "_type" : "_doc",
        "_id" : "JMxi8Hc0000OUUP9xbBZ",
        "_score" : 0.10404301,
        "_source" : {
          "name" : "Roberts beautiful book is a good option to your weekends.",
          "appearance-date" : 1938,
          "keywords" : [
            "happy",
            "sun",
            "sea"
          ]
        }
      }

I tried to follow this example but without success.

Thanks,
Ricardo

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.