How to get only exact matches for GUID via Nest 6.5

Hello,

I have following index, in which I labeled the 'Id' as 'Keyword':

[ElasticsearchType(IdProperty = nameof(Id))]
public class MyIndexModel
{
    [Keyword]
    public Guid Id { get; set; }

    [Text]
    public string SomeString{ get; set;}
 }

If I do following query on the index:

 var searchResponse = await this.elasticClient
            .SearchAsync<MyIndexModel>(
                s => s
                    .Index(MyIndexName)
                    .Size(1)
                    .PostFilter( pf => pf
                        .Bool( b => b.
                            Must( must => must
                            .Match(m => m
                                .Field(f => f.Id)
                                .Query(id.ToString()))))));

In which the 'id' in the last line is following GUID

'3B9BAAEE-AC35-E911-8E9E-D89EF315843C'

I get a result matching

'b859d1ff-ac35-e911-8e9e-d89ef315843c'.

The two Guids are similar but not the same. I thought that using the "Keyword" annotation guarantees that only exact matches are returned.

One further thing I've noticed is that the mapping for properties marked with "Keyword" and those marked with "Text" looks the same :

{
  "mapping": {
    "myindexmodel": {
      "properties": {
        "id": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        },
        "somestring": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        }
      }
    }
  }
}

What am I missing? How do I get only exact matches for GUID via Nest 6.5?

Thanks,

Art

I found the solution: using "MatchPhrase" instead of "Match" does the trick :slight_smile:

1 Like

For a keyword field like Id where you are looking for an exact match, you should use a term query, so that the query input does not undergo analysis.

Additionally, you should move the bool query out of .PostFilter(...) and into .Query(...), since the search request has no aggregations, so there is no need to use post_filter in this instance.

One more thing, since the bool query contains only a single query, there's no need to wrap it in a bool query, so you can specify the term query directly in .Query(q => q.Term(...)).

2 Likes

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.