首页 > 解决方案 > 使用 Elastic search dsl python analyze api

问题描述

如何在弹性搜索dsl python中使用默认_analyze?

我的查询如下所示:

query = Q('regexp', field_name = "f04((?!z).)*")
search_obj = Search(using = conn, index = index_name, doc_type = type_name).query(query)
response = search_obj[0:count].execute()

我在哪里放analyze() method,以便我可以看到我"f04((?!z).)*"是如何被分解的?实际上,它似乎'!'不能用作正则表达式。'!'如果默认分析器无法作为正则表达式字符,我该如何更改分析器?

我是新手,很难准确地将分析方法放入我的代码中。请帮忙。

标签: pythonregexelasticsearchelasticsearch-dslelasticsearch-dsl-py

解决方案


我不确定你到底想要达到什么目的。如果您发布了一个 CURL 查询,它可以满足您的需求,则可以更轻松地将其转换为 Elasticsearch DSl 或 elasticsearch-py 界面。

如果您正在寻找方法的替代_analyze方法,但在 Python 中,您可以使用 elasticsearch-py 来实现它,但我不确定您是否可以使用 Elasticsearch DSL 来实现。因此,假设我想查看如何jestem biały miś使用名为 的分析器分析我的字符串的结果morfologik。使用 CURL 我会运行:

$ curl -XGET "http://localhost:9200/morf_texts/_analyze" -H 'Content-Type: application/json' -d'
{
  "analyzer": "morfologik",
  "text": "jestem biały miś"
}'

{
  "tokens": [
    {
      "token": "być",
      "start_offset": 0,
      "end_offset": 6,
      "type": "<ALPHANUM>",
      "position": 0
    },
    {
      "token": "biały",
      "start_offset": 7,
      "end_offset": 12,
      "type": "<ALPHANUM>",
      "position": 1
    },
    {
      "token": "miś",
      "start_offset": 13,
      "end_offset": 16,
      "type": "<ALPHANUM>",
      "position": 2
    },
    {
      "token": "misić",
      "start_offset": 13,
      "end_offset": 16,
      "type": "<ALPHANUM>",
      "position": 2
    }
  ]
}

为了使用 elasticsearch-py 获得相同的结果,您可以运行以下命令:

from elasticsearch import Elasticsearch
from elasticsearch.client import IndicesClient

client = Elasticsearch()
indices_client = IndicesClient(client)

indices_client.analyze(
    body={
        "analyzer": "morfologik",
        "text": "jestem biały miś",
    }
)

analyze方法的输出与上述 CURL 请求相同:

{'tokens': [{'token': 'być',
   'start_offset': 0,
   'end_offset': 6,
   'type': '<ALPHANUM>',
   'position': 0},
  {'token': 'biały',
   'start_offset': 7,
   'end_offset': 12,
   'type': '<ALPHANUM>',
   'position': 1},
  {'token': 'miś',
   'start_offset': 13,
   'end_offset': 16,
   'type': '<ALPHANUM>',
   'position': 2},
  {'token': 'misić',
   'start_offset': 13,
   'end_offset': 16,
   'type': '<ALPHANUM>',
   'position': 2}]}

推荐阅读