Searching ElasticSearch using NEST C# Client

≯℡__Kan透↙ 提交于 2019-12-03 03:28:31

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);

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.

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!