Search code examples
elasticsearchrangenest

Elastic nest accessing sub property of text type


I have created text property name also i have created sub property as words_count of name and i want to have range query on words_count of name. How can i access it in c# using Nest.

"mappings": {
"person": {
  "properties": {
    "name": { 
      "type": "text",
      "fields": {
        "keyword": { 
          "type": "keyword"
        },
        "words_count": { 
          "type": "token_count",
          "analyzer": "standard"
        },
        "length": { 
          "type": "token_count",
          "analyzer": "character_analyzer"
        }
      }
    }
  }
}
}

I have length of name but its from c# string length. I want access words_count sub property of name created in elastic.

c# code

Func<QueryContainerDescriptor<MyType>, QueryContainer> query = m => m
                                    .Range(r => r.Field(f => f.name.words_count).Relation(RangeRelation.Within)
                                    .GreaterThanOrEquals(10).LessThanOrEquals(14));

I want replacement for f.name.words_count from elastic nest. do i need to create class for name having property length.


Solution

  • You don't need to create a POCO property to map to a multi-field (also often referred to as fields or sub-fields).

    They are functionality to be able to index a single input in multiple different ways, which is very common for search use cases. For example, indexing a street address with multiple different types of analysis.

    You can use the .Suffix(...) extension method to reference a multi-field

    Func<QueryContainerDescriptor<MyType>, QueryContainer> query = m => m
        .Range(r => r
            .Field(f => f.name.Suffix("words_count"))
            .Relation(RangeRelation.Within)
            .GreaterThanOrEquals(10)
            .LessThanOrEquals(14)
        );