Searching ElasticSearch using NEST C# Client

前端 未结 4 1182
-上瘾入骨i
-上瘾入骨i 2021-02-06 10:37

I started looking around for a search engine and after some reading I decided going with ElasticSearch (which is quite amazing :)), my project is in C# so I looked around for a

相关标签:
4条回答
  • 2021-02-06 11:19

    I just use the string query version: create my query object using C# anonymous type and serialize it to JSON.

    That way, I can have straightforward mapping from all the JSON query examples out there, no need translating into this "query DSL".

    Elasticsearch by itself evolves quite rapidly, and this query DSL thus is bound to lack some features.

    Edit: Example:

    var query = "blabla";
    var q = new
            {
                query = new
                {
                    text = new
                    {
                        _all= query
                    }
                }, 
                from = (page-1)*pageSize, 
                size=pageSize
            };
            var qJson = JsonConvert.SerializeObject(q);
            var hits = _elasticClient.Search<SearchItem>(qJson);
    
    0 讨论(0)
  • 2021-02-06 11:23

    If the anonymous types above aren't your thing, you can just use JObjects from json.net and build your query that way. Then you can run it the same way above.

    JObject query = new JObject();
    query["query"] = new JObject();
    query["query"]["text"] = new JObject();
    query["query"]["text"]["_all"] = searchTerm;
    query["from"] = start;
    query["size"] = maxResults;
    string stringQuery = JsonConvert.SerializeObject(query);
    var results = connectedClient.SearchRaw<SearchItem>(stringQuery);
    

    I like this way better because the DSL in ES uses reserved keywords in C#, like bool, so I don't have to do any escaping.

    0 讨论(0)
  • 2021-02-06 11:25

    With ElasticSearch 2.0, I have to use a SearchResponse< NewType > in the Search method like this :

    var json = JsonConvert.SerializeObject(searchQuery);
    var body = new PostData<object>(json);
    var res = _elasticClient.Search<SearchResponse<NewType>>(body);
    IEnumerable<NewType> result = res.Body.Hits.Select(h => h.Source).ToList();
    

    Hope it help.

    Note: I found very few documentation about PostData class and its generic type parameter

    0 讨论(0)
  • 2021-02-06 11:27

    Just to confirm

    elasticClient.Search<NewType>(s => s.Query(q => q.QueryString(d => d.Query(queryString))));

    Is the preferred way to search and the fact it feels a bit long is because there are alot of options you can play with that are not used here. I'm always open on suggestions to make it shorter!

    The string overload is deprecated but wont be removed from NEST. I'll update the obsolete message to explicitly mention this.

    0 讨论(0)
提交回复
热议问题