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
字段就有两个属性了分别是text
和keyword
,city
字段可以用作全文检索,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 analyzer
和english analyzer
解析,词根接受包含foxes
和fox
的文档,因此可以匹配更多的文档。通过查询词根可以提高文档的相关性。