ES之自动补全功能

in ELK with 0 comment

Elasticsearch的自动补全功能是基于suggest来实现的,但是需要提前定义好需要进行搜索字段的mapping信息

mapping一旦创建好后是不能修改的。

A. 定义mapping并执行。需要自动补全的属性的type必须是 completion

{"mappings" : {
    "properties" : {
        "@version" : {
        "type" : "text",
        "fields" : {
            "keyword" : {
                    "type" : "keyword",
                    "ignore_above" : 256
                }
            }
    },
    "genre" : {
        "type" : "completion",
        "fields" : {
        "keyword" : {
            "type" : "keyword",
            "ignore_above" : 256
            }
        }
    },
    "id" : {
        "type" : "text",
        "fields" : {
            "keyword" : {
                "type" : "keyword",
                "ignore_above" : 256
            }
        }
    },
    "title" : {
        "type" : "completion",
        "fields" : {
            "keyword" : {
                "type" : "keyword",
                "ignore_above" : 256
            }
        }
    },
    "year" : {
        "type" : "long"
        }
    }
}}

执行如下命令,重新定义mapping

put movies

B. 执行推荐

GET movies/_search
{
    "suggest": {
    "title-suggest": {
        "prefix": "bokx",
        "completion": {
            "field": "title"
            }
        }
    }
}

不足:completion这个推荐的方式只能是前缀查询,但是其查找速度极快。

Responses