Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reuse query for both count and search in Nest ElasticSearch

Is there a means to reuse a fluent query for both a Client.Search and a Client.Count in ElasticSearch via Nest?

Here is the start of a snippet defining a search fluent definition.

 System.Func<SearchDescriptor<Documents.City>, ISearchRequest> x = s => 
 s.Index(IndexNames.Cities).From(0)
   .Size(100)
   .Query(q => q.Bool(.....

The change for count would be SearchDescriptor -> CountDescriptor and ISearchRequest -> ICountRequest. It appears that the query needs to be written twice as the fluent markup will not compile without upfront knowledge of the types at play.

The essential question is, are there any neat maintainable methods for using a Nest query to execute both Search and Count requests?

like image 559
Techlead Avatar asked Jun 18 '18 14:06

Techlead


People also ask

How do I increase Elasticsearch score?

Just add a "boost" field or similar with a numerical value and order by that first in your query (and by score second).

What are hits in Elasticsearch?

A search consists of one or more queries that are combined and sent to Elasticsearch. Documents that match a search's queries are returned in the hits, or search results, of the response.

What is score in Elasticsearch query?

The score represents how relevant a given document is for a specific query. The default scoring algorithm used by Elasticsearch is BM25.


1 Answers

Instead of reusing search part, try to do it with query:

Func<QueryContainerDescriptor<T>, QueryContainer> query =
    q => q.MatchAll();

var searchResponse = await ElasticClient().SearchAsync<T>(s => s
    .Query(query));

var countResponse = await ElasticClient().CountAsync<T>(s => s.Query(query));

Hope that helps.

like image 195
Rob Avatar answered Nov 14 '22 04:11

Rob