概念
completion suggester会考虑索引中的所有文档,但有些情况下我们希望在复合一定的过滤条件的范围内获得suggest。例如,您想建议由某些艺术家的歌曲标题,或者您要根据其类型来提升某些歌曲标题的权重。
为了实现过滤或增强suggest,您可以在配置completion字段的mapping时添加上context mappings。可以为completion字段定义多个上context mappings。每个context mappings都有唯一的name和type。有两种type:category 和 geo。上下文映射在字段映射中的contexts参数下配置。
创建索引mapping
创建索引mapping有两种方式:
- 定义context名称和类型,在index的时候必须提供这个context的内容
PUT test1
{
"mappings":{
"properties": {
"suggest": {
"type": "completion",
"contexts": [
{
"name": "place_type",
"type": "category"
},
{
"name": "location",
"type": "geo",
"precision": 4
}
]
}
}
}
}
- 定义了place_type context的内容从path映射的值中读取, 在index的时候不用再提供这个context的内容了,只需要提供cat的内容
PUT test2
{
"mappings": {
"properties" : {
"suggest" : {
"type" : "completion",
"contexts": [
{
"name": "place_type",
"type": "category",
"path": "cat"
},
{
"name": "location",
"type": "geo",
"precision": 4,
"path": "loc"
}
]
},
"loc": {
"type": "geo_point"
}
}
}
}
插入数据
PUT test1/_doc/1
{
"suggest": {
"input": ["timmy's", "starbucks", "dunkin donuts"],
"contexts": {
"place_type": ["cafe", "food"]
}
}
}
PUT test2/_doc/1
{
"suggest": ["timmy's", "starbucks", "dunkin donuts"],
"cat": ["cafe", "food"]
}
查询数据
POST test1/_search?pretty
{
"suggest": {
"place_suggestion" : {
"prefix" : "tim",
"completion" : {
"field" : "suggest",
"size": 10,
"contexts": {
"place_type": [ "cafe", "restaurants" ]
}
}
}
}
}
OR
POST test1/_search?pretty
{
"suggest": {
"place_suggestion" : {
"prefix" : "tim",
"completion" : {
"field" : "suggest",
"size": 10,
"contexts": {
"place_type": [
{ "context" : "cafe" },
{ "context" : "restaurants", "boost": 2 }
]
}
}
}
}
}
返回结果
{
"took": 3,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 0,
"relation": "eq"
},
"max_score": null,
"hits": []
},
"suggest": {
"place_suggestion": [
{
"text": "tim",
"offset": 0,
"length": 3,
"options": [
{
"text": "timmy's",
"_index": "place",
"_type": "_doc",
"_id": "1",
"_score": 1,
"_source": {
"suggest": {
"input": [
"timmy's",
"starbucks",
"dunkin donuts"
],
"contexts": {
"place_type": [
"cafe",
"food"
]
}
}
},
"contexts": {
"place_type": [
"cafe"
]
}
}
]
}
]
}
}