【问题标题】:How to apply search in Elasticsearch in python with and without whitespces如何在带有和不带有whitespces的python中的Elasticsearch中应用搜索
【发布时间】:2018-02-26 00:45:42
【问题描述】:

我正在 python 中使用 ElasticSearch 构建搜索系统。我加载了一个 csv 并创建了一个搜索索引。

from elasticsearch import helpers, Elasticsearch
import csv

es = Elasticsearch()

with open('/Users/anubhav/Office/elasticsearch-5.6.0/all_products.csv') as f:
    reader = csv.DictReader(f)
    helpers.bulk(es, reader, index='product-index', doc_type='product-index')

es.indices.create(
    index='product-index',
    body={
      "settings": {
        "analysis": {
          "analyzer": {
            "my_analyzer": {
              "tokenizer": "my_tokenizer"
            }
          },
          "tokenizer": {
            "my_tokenizer": {
              "type": "edge_ngram",
              "min_gram": 2,
              "max_gram": 10,
              "token_chars": [
                "letter",
                "digit",
                "whitespace"
              ]
            }
          }
        }
      }
    },
    # Will ignore 400 errors, remove to ensure you're prompted
    ignore=400
)

response = es.search(
index='product-index',
body={
    "query": {
        "match": {
            "product": "PD5MP2 price"
        }
    },
    "aggs": {
        "top_10_states": {
            "terms": {
                "field": "state",
                "size": 10
            }
        }
    }
}
)

print response

csv 看起来像:

当我搜索时:

res = es.search(index="product-index", doc_type="product-index", body={"query": {"match": {"product": "DD 350"}}})

这很好用,因为确切的产品在 CSV 中。但是当我将查询更改为

res = es.search(index="product-index", doc_type="product-index", body={"query": {"match": {"product": "DD350"}}})

它不起作用。有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: python csv elasticsearch


    【解决方案1】:

    默认情况下,Elasticsearch 使用Standant Tokenizer 将文本划分为单词边界上的术语,由 Unicode 文本分割算法定义。这意味着DD 350 将被标记为DD, 350。当您搜索时,搜索关键字也将被标记为相同的标记器。因此,当您搜索 DD 350 时,Elasticsearch 将同时查找 DD350 并且两者都在您的索引中。但是当您搜索DD350 时,Elasticsearch 将无法找到它的索引。您应该检查tokenizers 及其用法。

    【讨论】:

    • 我已经用我正在使用的当前代码更新了这个问题。但是当我删除设置中的“忽略 400”行时,它给了我一个错误,说“索引已经存在”。你能不能也给我推荐一下这个标记器?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-29
    • 1970-01-01
    • 1970-01-01
    • 2014-08-18
    • 2022-06-21
    • 2013-05-18
    • 2023-03-15
    相关资源
    最近更新 更多