ElasticSearch 中的中文分词器以及索引基本操作详解
from datetime import datetime
from elasticsearch import Elasticsearch
# 连接ElasticSearch
es = Elasticsearch(hosts=["localhost:9200"])
# 创建或更新索引
def create_or_update_index(index_name, index_body):
if es.indices.exists(index_name):
es.indices.put_mapping(index=index_name, body=index_body)
print(f"Index {index_name} updated.")
else:
es.indices.create(index=index_name, body=index_body)
print(f"Index {index_name} created.")
# 创建文档
def create_document(index_name, doc_id, document):
es.index(index=index_name, id=doc_id, document=document)
print(f"Document {doc_id} added to index {index_name}.")
# 查询文档
def search_document(index_name, query):
response = es.search(index=index_name, body=query)
print(f"Search results for index {index_name}:")
for hit in response['hits']['hits']:
print(hit)
# 定义索引映射
index_body = {
"mappings": {
"properties": {
"content": {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_max_word"
},
"publish_date": {
"type": "date"
}
}
}
}
# 定义索引名称
index_name = "news_index"
# 创建或更新索引
create_or_update_index(index_name, index_body)
# 创建文档
doc_id = 1
document = {
"content": "这是一条测试新闻",
"publish_date": datetime.now()
}
create_document(index_name, doc_id, document)
# 查询文档
query = {
"query": {
"match": {
"content": "测试"
}
}
}
search_document(index_name, query)
这段代码首先导入了必要的Elasticsearch模块,并创建了与本地Elasticsearch实例的连接。然后定义了一个函数来创建或更新索引,并根据需要设置了中文分词器ik_max_word
。接着,定义了文档的索引映射和索引名称,并调用相应的函数来执行索引的创建或更新,以及文档的添加和搜索。这个例子展示了如何在Elasticsearch中使用中文分词器处理文本数据,并执行基本的索引和搜索操作。
评论已关闭