Search code examples
.netelasticsearchnest

Elasticsearch "must" query isn't mapping of index


I don't make query in elasticsearch for .net core with must operator. I use .net 5, Elasticsearch 7.16.0, NEST 7.16.0.

BeginDate = BeginDate == null ? DateTime.Parse("01/01/1900") : BeginDate;
        EndDate = EndDate == null ? DateTime.Now : EndDate;
        var response = _client.Search<LogModel>(s => s
       .From(page)
       .Size(rowCount)
       .Sort(ss => ss.Descending(p => p.PostDate))
       .Query(q => q
           .Bool(b => b
               .Must(
                   q => q.Term(t => t.LogType, "INFO"),
                   q => q.Term(t => t.RegionCode, RegionCode),
                   q => q.DateRange(dr => dr
                   .Field(p => p.PostDate)
                   .GreaterThanOrEquals(DateMath.Anchored(((DateTime)BeginDate).AddDays(-1)))
                   .LessThanOrEquals(DateMath.Anchored(((DateTime)EndDate).AddDays(1)))
                   ))
                )
             )
       .Index(indexName)
       );
        return response.Documents;

Solution

  • If you want to use Term queries, you actually need to run them on the keyword sub-field, like this:

    ...
    q => q.Term(t => t.LogType.Suffix("keyword"), "INFO"),
    q => q.Term(t => t.RegionCode.Suffix("keyword"), RegionCode),
    ...