Elasticsearch ik+pinyin搜索配置

Mapping设置

#!/usr/bin/env bash
#curl -XPUT http://127.0.0.1:9200/my/
curl -XPUT 'http://127.0.0.1:9200/my/mytype/_mapping' -d '
{
    "mytype3" : {
        "properties": {
           "title" : {
            "type" : "string",
            "analyzer": "ik",
            "searchAnalyzer": "ik"
          },
            "content" : {
            "type" : "string",
            "analyzer": "pinyin_analyzer",
            "searchAnalyzer": "pinyin_analyzer"
          }
        }
    }
}'

Setting设置

#!/usr/bin/env bash
curl -XPOST 'http://127.0.0.1:9200/my/_close'

curl -XPUT 'http://127.0.0.1:9200/my/_settings' -d '
{
   "index" : {
        "analysis" : {
            "analyzer" : {
                "ik_max_word" : {
                    "type": "ik",
                    "use_smart": false
                 },
                 "ik_smart": {
                    "type": "ik",
                    "use_smart": true
                 },
                "pinyin_analyzer" : {
                    "type":"custom",
                    "tokenizer" : "ik_smart",
                    "filter" : ["my_pinyin","snowball", "word_delimiter"]
                }
            },
            "filter" : {
                "my_pinyin" : {
                    "type" : "pinyin",
                    "first_letter" : "prefix",
                    "padding_char" : " "
                }
            }
        }
    }
}'
curl -XPOST 'http://127.0.0.1:9200/my/_open'

导入索引数据

curl -XPUT 'http://127.0.0.1:9200/my/mytype/1' -d '
{
  "title":"阿司匹林",
  "content":"阿司匹林药性药效",
}
'
curl -XPUT 'http://127.0.0.1:9200/my/mytype/2' -d '
{
  "title":"阿莫西林",
  "content":"阿莫西林抗生素",
}
'
curl -XPUT 'http://127.0.0.1:9200/my/mytype/3' -d '
{
  "title":"阿奇霉素",
  "content":"阿奇霉素副作用",
}
'

搜索结果测试

curl -XPOST 'http://127.0.0.1:9200/my/newtype/_search?pretty=true' -d '
{
  "query": {
    "multi_match": {
      "query": "a mo xi lin",
      "fields": [
        "title",
        "content"
      ],
      "operator": "and"
    }
  }
}'
或者
curl -XPOST 'http://127.0.0.1:9200/my/newtype/_search?pretty=true' -d '
{
  "query": {
    "multi_match": {
      "query": "阿莫西林",
      "fields": [
        "title",
        "content"
      ],
      "operator": "and"
    }
  }
}'

结果就是我们想要的数据

{
  "took": 2,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 1,
    "max_score": 3.0224097,
    "hits": [
        {
          "_index": "my",
          "_type": "newtype",
          "_id": "187",
          "_score": 3.0224097,
          "_source": {
             "title": "阿莫西林",
             "content": "阿莫西林抗生素",
          }
       }
    ]
  }
}


2 评论

发表评论

电子邮件地址不会被公开。 必填项已用*标注