仅索引ElasticSearch中的单个对象字段

时间:2015-12-30 14:15:07

标签: elasticsearch

想象一下,我有一些文档与其他类型的文档有关系,比如 building region 相关:

building:
  country: region
  city: region
  nearbyParks: [region]
  closestNuclearHideout: region

我需要能够通过与构建相关的任何区域执行搜索,因此我将此结构转换为:

building:
  countryId: <uuid>
  cityId: <uuid>
  nearbyParkIds: [<uuid>]
  closestNuclearHideoutId: <uuid>
  regions: [region]

但是,到目前为止,我只需要通过相关的区域ID执行搜索,并且希望禁止ElasticSearch为每个regions.*字段(regions.id除外)编制索引以保持清洁。这可能使用当前的映射API吗?我希望保持我的弹性文档尽可能小,并使它们与后端输出保持同步,因此添加regionIds uuid数组字段是一个选项,但是不需要的。

1 个答案:

答案 0 :(得分:1)

是的,您可以关闭给定字段的dynamic映射。因此,在映射中,您可以定义想要映射的字段,同时有效地禁用其余的搜索。

{
  "mappings": {
    "type": {
      "properties": {
        "regions": {
          "type": "object",
          "dynamic": false,
          "properties": {
            "id": {
              "type": "string",
              "index": "not_analyzed",
              "doc_values" : true
            }
          }
        }
      }
    }
  }
}

所以,想象你为这个文档编制了索引:

{
  "regions" : [
    {
      "id" : "xyzabc",
      "field1" : "ignored",
      "field2" : "ignored"
    },
    {
      "id" : "abcdef",
      "field1" : "ignored",
      "field2" : "ignored",
      "field3" : "ignored"
    }
  ]
}

映射会忽略非id字段,因此它们无法搜索(没有脚本),但 会将其作为_source取回导致你的命中。