Home > Software design >  Match exact phrase using elasticsearch Nest
Match exact phrase using elasticsearch Nest

Time:01-06

I'm using Nest to build a query. I have a class called Event which has a property called Location and a property called Address (a string). So the indices look something like this:

"id" : "something1",
"location": {
    "address": "The Club",
}

"id" : "something2",
"location": {
    "address": "The Hole",
}

I want to create a query where the user types "The Club" (the location variable) and it only retrieves the first item that has "The Club" as the address

This is my current query

  var skip = (page - 1) * rows;
  var searchResponse = await _elasticClient.SearchAsync<Event>(s => s
            .From(skip)
            .Size(rows)
            .Query(q => q
                .QueryString(qs => qs
                    .Fields(fields => fields
                        .Field(f => f.Location.Address)
                    )
                    .Analyzer("keyword")
                    .Query("*"   (location ?? string.Empty)   "*")
                )
            ));

Currently, the query retrieves both objects since it finds "The". Do I need to add something to my index previously or what should I do?

For the record I added this when creating the index but it has no effect

 client.Indices.Create(eventsIndex, c => c.Map<Event>(m => m
        .Properties(p => p
            .Text(t => t
                .Name(n => n.Location.Address)
                    .Analyzer("keyword"))
            )
        ));

CodePudding user response:

I have two suggestions:

1 - Add the stop filter (default language english) that way you won't produce tokens like the term "the", all stopwords will be removed. Now you will only match the term "hotel", the term "the" will be filtered out.

POST _analyze
{
  "tokenizer": "standard",
  "filter": ["stop"], 
  "text": ["the hotel"]
}

Token

{
  "tokens": [
    {
      "token": "hotel",
      "start_offset": 4,
      "end_offset": 9,
      "type": "<ALPHANUM>",
      "position": 1
    }
  ]
}

2 - Use the default_operator AND in Query String query.

  • Related