如何在ElasticSearch中找到以序列开头单词或短语?

bvjveswy  于 2022-12-26  发布在  ElasticSearch
关注(0)|答案(2)|浏览(176)

假设我有这些数据

[
    {
        name: "Apple Company"
    },
    {
        name: "Microsoft Company"
    }
]

我想得到这样的查询结果:
查询1:

name: apple

结果1:

[
    {
        name: "Apple Company"
    }
]

查询2:

name: app

结果2:

[
    {
        name: "Apple Company"
    }
]

查询3:

name: apple com

结果3:

[
    {
        name: "Apple Company"
    }
]

查询4:

name: apple company

结果4:

[
    {
        name: "Apple Company"
    }
]

查询5:

name: company

结果5:

[
    {
        name: "Apple Company"
    },
    {
        name: "Microsoft Company"
    }
]

查询6:

name: ap com

结果6:

[]

如何在elasticsearch中做到这一点?

uyto3xhc

uyto3xhc1#

您可以使用elasticsearch中的Shingle Token filter和前缀查询,这将涵盖您提到的所有场景:

索引Map:

{
  "settings": {
    "analysis": {
      "analyzer": {
        "english": {
          "tokenizer": "standard",
          "filter": [
            "my_shingle_filter",
            "lowercase"
          ]
        }
      },
      "filter": {
        "my_shingle_filter": {
          "type": "shingle",
          "min_shingle_size": 2,
          "max_shingle_size": 4,
          "output_unigrams": true
        }
      }
    }
  },
  "mappings": {
    "properties": {
      "name": {
        "type": "text",
        "analyzer": "english"
      }
    }
  }
}

查询:

{
  "query": {
    "prefix": {
      "name": {
        "value": "apple com"
      }
    }
  }
}
iq0todco

iq0todco2#

您可以使用query_string来搜索数据。
通过Kibana DevTools为您的数据建立索引。

POST test_autocomplete/_bulk
{"index":{}}
{"id":1,"name":"Apple Company"}
{"index":{}}
{"id":2,"name":"Microsoft Company"}

使用query_string搜索数据。

GET test_autocomplete/_search
{
  "query": {
    "query_string": {
      "default_field": "name",
      "query": "app* or mic*"
    }
  }
}

您还可以使用match_bool_prefix查询

GET test_autocomplete/_search
{
  "query": {
    "match_bool_prefix" : {
      "name": "co"
    }
  }
}

查询字符串的引用:https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html
自动完成参考:https://opster.com/guides/elasticsearch/how-tos/elasticsearch-auto-complete-guide/
下面是match_bool_prefix查询的结果。

相关问题