elasticsearch 查询时输入即搜索 类似百度输入框的自动完成

1.配置分词策略

PUT /my_index HTTP/1.1
Host: localhost:9200
Content-Type: application/json
Content-Length: 647

{
    "settings": {
        "number_of_shards": 1, 
        "analysis": {
            "filter": {
                "autocomplete_filter": { 
                    "type":     "edge_ngram",
                    "min_gram": 1,
                    "max_gram": 20
                }
            },
            "analyzer": {
                "autocomplete": {
                    "type":      "custom",
                    "tokenizer": "standard",
                    "filter": [
                        "lowercase",
                        "autocomplete_filter" 
                    ]
                }
            }
        }
    }
}

2.验证分词器

GET /my_index/_analyze HTTP/1.1
Host: localhost:9200
Content-Type: application/json
Content-Length: 62

{
    "analyzer":"autocomplete",
    "text":"quick brown"
}

3设置索引字段对分词器生效 ,类似mysql 声明表结构

PUT /my_index/_mapping/my_type?include_type_name=true HTTP/1.1
Host: localhost:9200
Content-Type: application/json
Content-Length: 184

{
    "my_type": {
        "properties": {
            "name": {
                "type":     "text",
                "analyzer": "autocomplete"
            }
        }
    }
}

 

4.批量插入验证数据

PUT /my_index/my_type/_bulk HTTP/1.1
Host: localhost:9200
Content-Type: application/json
Content-Length: 135

{ "index": { "_id": 1            }}
{ "name": "Brown foxes"    }
{ "index": { "_id": 2            }}
{ "name": "Yellow furballs" }

5.执行查询

POST /my_index/my_type/_search HTTP/1.1
Host: localhost:9200
Content-Type: application/json
Content-Length: 90

{
    "query": {
        "match": {
            "name": "brown fo"
        }
    }
}

6.优化,使用standard 分析器效果更好

POST /my_index/my_type/_search HTTP/1.1
Host: localhost:9200
Content-Type: application/json
Content-Length: 175

{
    "query": {
        "match": {
            "name": {
                "query": "brown fox",
                "analyzer": "standard"
            }
        }
    }
}

7.使用explain 分析

POST /my_index/my_type/_validate/query?explain=null HTTP/1.1
Host: localhost:9200
Content-Type: application/json
Content-Length: 90

{
    "query": {
        "match": {
            "name": "brown fo"
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值