fields(字段)

fields(字段)

我们经常会因为不同的目的将同一个字段用不同的方式索引。这就相当于实现了multi-fields。例如,一个string类型字段可以被映射成text字段作为full-text进行搜索,同时也可以作为keyword字段用于排序和聚合:

curl -XPUT 'localhost:9200/my_index?pretty' -H 'Content-Type: application/json' -d'
{
  "mappings": {
    "my_type": {
      "properties": {
        "city": {
          "type": "text",
          "fields": {
            "raw": { #1
              "type":  "keyword"
            }
          }
        }
      }
    }
  }
}
'
curl -XPUT 'localhost:9200/my_index/my_type/1?pretty' -H 'Content-Type: application/json' -d'
{
  "city": "New York"
}
'
curl -XPUT 'localhost:9200/my_index/my_type/2?pretty' -H 'Content-Type: application/json' -d'
{
  "city": "York"
}
'
curl -XGET 'localhost:9200/my_index/_search?pretty' -H 'Content-Type: application/json' -d'
{
  "query": {
    "match": {
      "city": "york" #2
    }
  },
  "sort": {
    "city.raw": "asc" #3
  },
  "aggs": {
    "Cities": {
      "terms": {
        "field": "city.raw" #4
      }
    }
  }
}
'

备注

Multi_fields不会改变原始的_source字段。

注意

同一索引相同字段名可以设置不同的fields。可以通过PUT mapping API 在已经存在的字段加入新的multi-fields

Multi-fields with multiple analyzers(多分析器处理多字段)

multi-fields 的另一种使用情况是同一字段使用不同的解析方式,使其能更好的检索。例如,我们可以用标准分析器对字段进行索引,它将文本分解为单词,再用英文分析器将单词分成词根:

curl -XPUT 'localhost:9200/my_index?pretty' -H 'Content-Type: application/json' -d'
{
  "mappings": {
    "my_type": {
      "properties": {
        "text": { #1
          "type": "text",
          "fields": {
            "english": { #2
              "type":     "text",
              "analyzer": "english"
            }
          }
        }
      }
    }
  }
}
'
curl -XPUT 'localhost:9200/my_index/my_type/1?pretty' -H 'Content-Type: application/json' -d'
{ "text": "quick brown fox" } #3
'
curl -XPUT 'localhost:9200/my_index/my_type/2?pretty' -H 'Content-Type: application/json' -d'
{ "text": "quick brown foxes" } #4
'
curl -XGET 'localhost:9200/my_index/_search?pretty' -H 'Content-Type: application/json' -d'
{
  "query": {
    "multi_match": {
      "query": "quick brown foxes",
      "fields": [ #5
        "text",
        "text.english"
      ],
      "type": "most_fields" #6
    }
  }
}
'

text字段在第一个文档中包含词根 fox,在第二个文档中包含词根 foxestext.english 字段在两个文档同时包含词根 fox,因为 foxes fox 的衍生词。

字符串搜索会为 text 字段使用标准分析器解析,为text.english字段使用英文分析器解析。衍生字段将会使搜索 foxes 的同时匹配到 fox。这使我们能尽可能多的匹配到文档。同时,搜索没有衍生的 text 字段时,我们会在文档精确匹配foxes的时候提高其检索评分。

Last updated