且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在ElasticSearch/NEST中将单个.NET类型映射到多个嵌套对象类型?

更新时间:2021-12-10 08:54:09

如果我正确理解了您的意图,Entity对象将仅包含嵌套对象,不是吗?

If I understand correctly your intention, Entity object will have only nested objects in it, won't it?

您可以尝试将Elasticsearch的动态映射功能用于实体对象.我认为Entity是根对象.

You can try to use dynamic mapping functionality of elasticsearch for entity object. I assume Entity is a root object.

curl -X POST localhost:9200/myindex/entity/_mapping
{"dynamic_templates": [
    {"nested_data_template": {
        "mapping": {
            "type": "nested" },
        "match_mapping_type": "object",
        "path_match": "*" }}]}

path_match: *match_mapping_type: object表示对于所有以object为值的字段名称,将应用嵌套类型映射.

path_match: * and match_mapping_type: object mean that for all field names with object as a value nested type mapping will be applied.

使用NEST和Fluent API,您可以使用以下API. IntelliSense将指导您如何构建上面的映射. ;)

Using NEST and Fluent API you can use the following API. IntelliSense will guide you how to build mapping above. ;)

descriptor.DynamicTemplates(DynamicTemplatesDescriptor<Entity>)

每次出现与该模板匹配的新属性时,elasticsearch都会基于动态映射更新映射.一段时间后,您的映射将如下所示:

Every time when a new property matching this template appears, elasticsearch will update mapping based on dynamic mapping. After a while your mapping will look like:

{
  "entity": {
    "mappings": {
      "entity": {
        "dynamic_templates": [
          {
            "nested_data_template": {
              "mapping": {
                "type": "nested"
              },
              "match_mapping_type": "object",
              "path_match": "*"
            }
          }
        ],
        "properties": {
          "test": {
            "type": "nested",
            "properties": {
              "test": {
                "type": "string"
              },
              "another_property": {
                "type": "string"
              }
            }
          },
          "test1": {
            "type": "nested",
            "properties": {
              "test": {
                "type": "string"
              }
            }
          }
        }
      }
    }
  }
}

希望这会有所帮助!