elasticsearch mapping之fields

2022-07-22 12:09:36

ES允许同一个字段有两个不同的类型,例如一个字段可以拥有keyword类型来进行聚合与排序,也可以拥有text来做全文检索。
举例如下:

PUT my_index
{
  "mappings": {
    "type": {
      "properties": {
        "city": {
          "type": "text",
          "fields": {
            "raw": {
              "type": "keyword"
            }
          }
        }
      }
    }
  }
}

PUT my_index/type/1
{
  "city": "New York"
}

PUT my_index/_doc/2
{
  "city": "York"
}

GET my_index/_search
{
  "query": {
    "match": {
      "city": "york" 
    }
  },
  "sort": {
    "city.raw": "asc" 
  },
  "aggs": {
    "Cities": {
      "terms": {
        "field": "city.raw" 
      }
    }
  }
}

这样city字段就有两个属性了分别是textkeywordcity字段可以用作全文检索,city.raw可以用作排序和聚合。
此外还可以使用不同的analyzer,例如我们可以使用standard analyzer来进行分词,同时使用english analyzer来将单词转为词根。例如:

PUT my_index
{
  "mappings": {
    "properties": {
      "text": { 
        "type": "text", //text 这个使用`standard` analyzer
        "fields": {
          "english": { 
            "type":     "text",
            "analyzer": "english" // text.english使用`english ` analyzer
          }
        }
      }
    }
  }
}

PUT my_index/_doc/1
{ "text": "quick brown fox" } 

PUT my_index/_doc/2
{ "text": "quick brown foxes" } 

GET my_index/_search
{
  "query": {
    "multi_match": {
      "query": "quick brown foxes",
      "fields": [ 
        "text",
        "text.english"  
      ],  // text and text.english fields and combine the scores
      "type": "most_fields" 
    }
  }
}

text字段包含第一条数据中的fox和第二条数据中的foxes,而text.english字段包含两条数据中的fox,因为第二条数据的foxes的词根是fox
此外查询语句同样被standard analyzerenglish analyzer解析,词根接受包含foxesfox的文档,因此可以匹配更多的文档。通过查询词根可以提高文档的相关性。

  • 作者:vincent_duan
  • 原文链接:https://blog.csdn.net/vincent_duan/article/details/103969127
    更新时间:2022-07-22 12:09:36