使用Python操作ElasticSearch
Elasticsearch是一个基于Lucene的搜索引擎,它提供了一个可扩展的多用户全文搜索引擎。使用Python操作ElasticSearch可以非常方便地进行索引和搜索。
创建索引
在操作ElasticSearch之前,首先需要创建一个索引。下面是一个简单的Python代码示例,用于创建一个名为“my_index”的索引,并定义了一个类型“my_type”。
from elasticsearch import Elasticsearch
es = Elasticsearch()
index_name = 'my_index'
index_type = 'my_type'
if es.indices.exists(index_name):
es.indices.delete(index=index_name)
es.indices.create(index=index_name, ignore=400)
mapping = {
"properties": {
"title": {"type": "text"},
"content": {"type": "text"}
}
}
es.indices.put_mapping(index=index_name, doc_type=index_type, body=mapping)
查询数据
现在我们已经建立了一个索引,下面是一个Python代码示例,用于搜索“my_index”索引中包含“Python编程”关键字的文档。