Steve
Steve

Reputation: 393

Generate QueryString with named fields using nest elastic search client

Im currently using Nest elastic clien, so run basic search terms like this:

.Query(q => q.QueryString(qs=>qs.Query("user search term")));

and i'm also combining those basic search terms with facets filters like this:

.Query(
    q => q.QueryString(qs => qs.Query("user search term"))
    && q.Terms(t => t.Brand, new string[] {"brand1", "brand2"})
    && q.Terms(t => t.Colour, new string[] {"blue", "black"})
    && q.Range(r => r.From(50).To(100).OnField(f => f.Price))
);

however I'm struggling to run custom query string searches that apply to specific fields. The search querystring will be passed into my app and therefore i wont know the specific fields that im searching so i cannot use the .OnField() method on the client

For example a want to be able to pass in a querystring that searches by brand, gender and colour at the same time. From looking at the Elastic search query DSL I think I should be able to pass in a querystring that names the fields like so:

.Query(q => q.QueryString(qs => qs.Query("brand:brand1 AND gender:male AND colour(blue)")));

but this doesnt work and returns no results. How can I generate a querystring to search on specific fields the Nest client?

Also is there any way of viewing the generated query from the nest SearchDescriptor?

Upvotes: 3

Views: 3443

Answers (1)

Mohammad Hatami
Mohammad Hatami

Reputation: 289

You can use bool query

List<QueryContainer> shoudQuery = new List<QueryContainer>();

shoudQuery.Add(new MatchQuery()
    {
       Field = "brand",
       Query = "brand1",    
    });
shoudQuery.Add(new MatchQuery()
    {
       Field = "gender",
       Query = "male",    
    });
shoudQuery.Add(new MatchQuery()
    {
       Field = "colour",
       Query = "blue",    
    });


QueryContainer queryContainer = new BoolQuery
        {
             Should = shoudQuery.ToArray(),
             Must = new QueryContainer[] { new MatchAllQuery() },
             MinimumShouldMatch = 3,

         };


var result = Client.Search(s => s.Size(resultSize).Query(q => queryContainer)
  1. if you want 3 and =>MinimumShouldMatch = 3
  2. if you want 2 of 3 =>MinimumShouldMatch = 2

    ...

Upvotes: 2

Related Questions