要使用Python调用Elasticsearch并进行常见操作,可以使用elasticsearch-py库,这是Elasticsearch官方提供的Python客户端。下面是如何安装该库以及进行一些常见操作的步骤和对应代码。

安装elasticsearch-py

首先确保你已经安装了elasticsearch-py库。可以使用以下命令安装:

pip install elasticsearch

连接到Elasticsearch

from elasticsearch import Elasticsearch

# 创建一个Elasticsearch客户端实例
es = Elasticsearch([{'host': 'localhost', 'port': 9200}])

检查连接

# 检查Elasticsearch集群是否可用
if es.ping():
    print("Connected to Elasticsearch")
else:
    print("Could not connect to Elasticsearch")

创建索引

# 创建一个索引
index_name = 'my_index'
if not es.indices.exists(index=index_name):
    es.indices.create(index=index_name)
    print(f"Index '{index_name}' created.")
else:
    print(f"Index '{index_name}' already exists.")

添加文档

# 添加文档到索引
doc = {
    'author': 'John Doe',
    'text': 'Elasticsearch is a highly scalable open-source full-text search and analytics engine.',
    'timestamp': '2023-10-01'
}

resp = es.index(index=index_name, document=doc)
print(f"Document added with ID: {resp['_id']}")

获取文档

# 根据ID获取文档
doc_id = resp['_id']
retrieved_doc = es.get(index=index_name, id=doc_id)
print(f"Retrieved Document: {retrieved_doc['_source']}")

搜索文档

# 搜索文档
search_param = {
    "query": {
        "match": {
            "text": "Elasticsearch"
        }
    }
}

search_results = es.search(index=index_name, body=search_param)
print("Search results:")
for hit in search_results['hits']['hits']:
    print(hit['_source'])

更新文档

# 更新文档
update_doc = {
    'doc': {
        'text': 'Elasticsearch is an open-source search engine.'
    }
}

es.update(index=index_name, id=doc_id, body=update_doc)
updated_doc = es.get(index=index_name, id=doc_id)
print(f"Updated Document: {updated_doc['_source']}")

删除文档

# 删除文档
es.delete(index=index_name, id=doc_id)
print(f"Document with ID {doc_id} deleted.")

删除索引

# 删除索引
es.indices.delete(index=index_name)
print(f"Index '{index_name}' deleted.")

以上展示了如何使用Python与Elasticsearch进行基本的CRUD(创建、读取、更新、删除)操作


已禁言
1 声望0 粉丝