Using SearchBuilder in the NEST ElasticSearch Client

I was wondering if anyone has any tips or examples on using the SearchBuilder API in NEST. Documents are still rare.

I want to dynamically build queries / filters based on criteria sent in URL parameters. Example:

www.mydomain.com/things/search?prop1=3&prop2=foo&prop3=bar

And as soon as I extract those, I want to build an exact match query based on the criteria that are present.

+4
source share
2 answers

Using the DSL query syntax, you can simply do this:

var results = client.Search(s=>s .Fields(new string[0]) .Query(q=> q.Term(ESFields.City, city) && q.Term(ESFields.State, state) ) ); 

which relies on conditionless query support added in 0.9.10.0.

This will only trigger a city query if city contains a value and only a state expression query if state not null or empty.

  • If both values โ€‹โ€‹are valid, it will execute a bool request
  • If only one is valid, it will execute only one term request
  • If none of them is valid, it returns to match_all.
+3
source

Here is how I did it:

  var boolQuery = QueryFactory.BoolQuery(); if (!String.IsNullOrEmpty(city)) { boolQuery.Must(QueryFactory.TermQuery(ESFields.City, city)); } if (!String.IsNullOrEmpty(state)) { boolQuery.Must(QueryFactory.TermQuery(ESFields.State, state)); } //etc. for many fields var sb = SearchBuilder.Builder(); //I want no actual data - this will ensure I only get IDs sb.Fields(new string[0]); sb.Query(boolQuery); var companyIds = ((ElasticClient)_elasticClient).Search(sb, ESIndexes.Client, ESIndexTypes.Client, tenantId) .DocumentsWithMetaData.Select(d => d.Id).ToList(); 

Not sure if this is the most efficient / effective way to do this, but it works.

0
source

Source: https://habr.com/ru/post/1437474/


All Articles