簡體   English   中英

Python中的Elasticsearch,有詞組提示嗎?

[英]Elasticsearch in Python, is there a phrase suggestor?

此處點擊此鏈接。 有一個稱為“短語建議器”的概念,它使用一些 N-Gram 方法為您提供類似於自動完成的建議。 我試圖查看如何使用 Python 提供的 api 提供的文檔here 但我找不到任何提及 n-gram 或短語建議的內容。

Python Elasticsearch API中是否存在這種方法? 我知道 NLTK 和那里的 n-gram 方法。

這是我所擁有的。

首先連接,這段代碼工作正常

from elasticsearch import Elasticsearch
CLOUD_ID = 'My_deployment:...'
ELASTIC_PASSWORD = 'password'

es = Elasticsearch(cloud_id=CLOUD_ID,
    basic_auth=("elastic", ELASTIC_PASSWORD))

這第二個塊不起作用

text = 'noble prize'
suggest_dictionary = {"simple_phrase" : {
                      'text' : text,
                      "phrase" : {
                          "field" : "title.trigram"
                      }
                    }
                  }

query_dictionary = {'suggest' : suggest_dictionary}

res = es.search(
    index='test',
    body=query_dictionary)
print(res)

錯誤信息是這樣的

<ipython-input-29-05c434577314>:12: DeprecationWarning: The 'body' parameter is deprecated and will be removed in a future version. Instead use individual parameters.
  res = es.search(

---------------------------------------------------------------------------
NotFoundError                             Traceback (most recent call last)
<ipython-input-29-05c434577314> in <module>
     10 query_dictionary = {'suggest' : suggest_dictionary}
     11 
---> 12 res = es.search(
     13     index='test',
     14     body=query_dictionary)

~/anaconda3/lib/python3.8/site-packages/elasticsearch/_sync/client/utils.py in wrapped(*args, **kwargs)
    402                         pass
    403 
--> 404             return api(*args, **kwargs)
    405 
    406         return wrapped  # type: ignore[return-value]

~/anaconda3/lib/python3.8/site-packages/elasticsearch/_sync/client/__init__.py in search(self, index, aggregations, aggs, allow_no_indices, allow_partial_search_results, analyze_wildcard, analyzer, batched_reduce_size, ccs_minimize_roundtrips, collapse, default_operator, df, docvalue_fields, error_trace, expand_wildcards, explain, fields, filter_path, from_, highlight, human, ignore_throttled, ignore_unavailable, indices_boost, lenient, max_concurrent_shard_requests, min_compatible_shard_node, min_score, pit, post_filter, pre_filter_shard_size, preference, pretty, profile, q, query, request_cache, rescore, rest_total_hits_as_int, routing, runtime_mappings, script_fields, scroll, search_after, search_type, seq_no_primary_term, size, slice, sort, source, source_excludes, source_includes, stats, stored_fields, suggest, suggest_field, suggest_mode, suggest_size, suggest_text, terminate_after, timeout, track_scores, track_total_hits, typed_keys, version)
   3697         if __body is not None:
   3698             __headers["content-type"] = "application/json"
-> 3699         return self.perform_request(  # type: ignore[return-value]
   3700             "POST", __path, params=__query, headers=__headers, body=__body
   3701         )

~/anaconda3/lib/python3.8/site-packages/elasticsearch/_sync/client/_base.py in perform_request(self, method, path, params, headers, body)
    319                     pass
    320 
--> 321             raise HTTP_EXCEPTIONS.get(meta.status, ApiError)(
    322                 message=message, meta=meta, body=resp_body
    323             )

NotFoundError: NotFoundError(404, 'index_not_found_exception', 'no such index [test]', test, index_or_alias)

提供的答案指出使用PUT test來設置索引。 在哪里? 不知道...如何? 不知道......我不熟悉這種語法,Python 似乎也無法識別它。

更新

我終於能夠讓它工作了,但我對 output 感到困惑

{'took': 1, 'timed_out': False, '_shards': {'total': 1, 'successful': 1, 'skipped': 0, 'failed': 0}, 'hits': {'total': {'value': 0, 'relation': 'eq'}, 'max_score': None, 'hits': []}, 'suggest': {'simple_phrase': [{'text': 'Hi, I need help', 'offset': 0, 'length': 15, 'options': []}]}}

哪里有推薦? 又名自動完成來完成句子?

您可以先創建索引映射,這樣您就不需要在生成 NGram 后依賴外部 python Ngram 和內部 Elasticsearch 存儲字段。

索引映射

PUT test
{
  "settings": {
    "index": {
      "number_of_shards": 1,
      "analysis": {
        "analyzer": {
          "trigram": {
            "type": "custom",
            "tokenizer": "standard",
            "filter": ["lowercase","shingle"]
          }
        },
        "filter": {
          "shingle": {
            "type": "shingle",
            "min_shingle_size": 2,
            "max_shingle_size": 3
          }
        }
      }
    }
  },
  "mappings": {
    "properties": {
      "title": {
        "type": "text",
        "fields": {
          "trigram": {
            "type": "text",
            "analyzer": "trigram"
          }
        }
      }
    }
  }
}

您可以使用以下 python 代碼作為短語建議器,並提供與文檔中提到的相同的正文。

from elasticsearch import Elasticsearch
es = Elasticsearch()

text = 'noble prize'
suggest_dictionary = {"simple_phrase" : {
                      'text' : text,
                      "phrase" : {
                          "field" : "title.trigram"
                      }
                    }
                  }

query_dictionary = {'suggest' : suggest_dictionary}

res = es.search(
    index='test',
    body=query_dictionary)
print(res)

更新 1:

提供的答案指出使用 PUT 測試來設置索引。 在哪里? 不知道...如何? 不知道......我不熟悉這種語法,Python 似乎也無法識別它。

put test用於在 Elasticsearch 中創建索引。因此,如果您安裝了kibana ,則可以轉到dev console並執行它。 否則你也可以使用curl命令。 如果您有 exsitig 索引,那么您可以提供您的索引名稱以及test的 insted。

將展示如何使用 curl 命令創建索引。

將展示如何使用 python 創建索引。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM