使用Python操作Elasticsearch(进行注册和搜索)

目标或目的

    • pythonからElasticsearchを操作する

 

    python、Elasticsearchは別々のDockerコンテナで動作し、それぞれはdocker-composeで起動している

不做的事

    • docker-composeで行うDockerコンテナの起動方法(参考:DockerコンテナでElasticSearchを起動する(docker-compose))

 

    pythonの基礎知識(importとか)

环境

    • OS: macOS Catalina 10.15.4

 

    • Docker: 2.2.0.5

 

    • docker-compose: 1.25.4

 

    ElasticSearch: 7.4.2

做过的事情

创建注册处理

请参考构建时的帖子,了解在容器中使用pip安装和容器名称的相关信息(参考:在Docker容器中启动ElasticSearch(使用docker-compose))。

import os
import elasticsearch

# 接続先のElastisearchを指定(今回はElasticsearchのコンテナ名を指定)
client = elasticsearch.Elasticsearch("elasticsearch")

game = {}
game['title'] = 'hiroky quest'
game['genre'] = 1
game['release_date'] = '2020/05/01'
game['memo'] = 'memo'
# indexを指定して登録を行う
client.index(index='games', doc_type='_doc', body=game)

由于此次使用了Docker网络,因此需要指定容器名称。
如果是在本地启动的Elasticsearch,则需要指定为「localhost:9200」。

# 接続先のElastisearchを指定(今回はElasticsearchのコンテナ名を指定)
client = elasticsearch.Elasticsearch("elasticsearch")

索引对应于RDS表格(应该)存在,与RDS不同之处在于即使不创建索引也能执行注册,并自动添加索引。同时还会自动创建映射(类似RDS的表定义)。

# indexを指定して登録を行う
client.index(index='games', doc_type='_doc', body=game)

请搜索并确认注册信息。

import os
import elasticsearch

# Elasticsearchのコンテナ名を指定(Docker Network)
client = elasticsearch.Elasticsearch("elasticsearch")

# index指定で検索
result = client.search(
    index='games'
)
print(result)

用client.search进行搜索。在这种情况下,将对所有索引进行全文搜索。

# python3 search.py
{'took': 11, 'timed_out': False, '_shards': {'total': 1, 'successful': 1, 'skipped': 0, 'failed': 0}, 'hits': {'total': {'value': 1, 'relation': 'eq'}, 'max_score': 1.0, 'hits': [{'_index': 'games', '_type': '_doc', '_id': 'AAyn53EBfM-Vwr_FW_d7', '_score': 1.0, '_source': {'title': 'hiroky quest', 'genre': 1, 'release_date': '2020/05/01', 'memo': 'memo'}}]}}

你可以指定搜索条件并进行搜索。

import os
import elasticsearch

# Elasticsearchのコンテナ名を指定(Docker Network)
client = elasticsearch.Elasticsearch("elasticsearch")

# 条件検索
result = client.search(
    index='games',
    body={'query': {'match': {'genre': 1}}}
)

print(result)

在这种情况下,将获得与’genre’: 1相应的记录作为搜索结果。
‘match’会作为完全匹配来进行搜索。

印象

由于Python客户端的使用方法非常简单,所以我能轻松地实现它。
目前仅实现了简单的注册和搜索功能,希望能够深入使用它。

bannerAds