3
votes

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?

1
You can see what NEST is sending to Elasticsearch via this previous question: stackoverflow.com/questions/23703570/…Paige Cook
thank you seeing the json generated helped me realise that the query string generated using the nest client was exactly how i needed it to be, and therefore the problem was in my original mapping on the index. As a also generate term queries on the brand and gender fields they were set as FieldIndexOption.not_analyzed which was the problem.Steve

1 Answers

2
votes

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

    ...