python
import asyncio
import random
from typing import Optional
from elasticsearch import AsyncElasticsearch
class ESClientManager:
def __init__(self):
self.client:Optional[AsyncElasticsearch]=None
pass
def _get_url(self):
return f"http://127.0.0.1:9200"
pass
def init(self):
self.client=AsyncElasticsearch(hosts=self._get_url())
pass
async def close(self):
if self.client:
await self.client.close()
pass
es_client_manager=ESClientManager()
if __name__ == '__main__':
es_client_manager.init()
client=es_client_manager.client
index_name="product"
# async def test_index():
# result=await client.indices.exists(index=index_name)
#
# print(result)
#
# await es_client_manager.close()
#
#
#
# asyncio.run(test_index())
async def test_create():
result = await client.indices.exists(index=index_name)
if not result:
result = await client.indices.create(
index=index_name,
mappings={
"properties": {
"name": {
"type": "text",
# "analyzer": "ik_max_word" # 已修正拼写错误
"analyzer": "standard" # 已修正拼写错误
},
"brand": {
"type": "keyword"
},
"price": {
"type": "float"
}
}
}
)
print(result)
# 无论索引是否已存在,都确保关闭连接
await es_client_manager.close()
#asyncio.run(test_create())
async def test_add_doc():
result=await client.index(
index=index_name,
document={
"name":"huawei华为手机meta80",
"brand":"华为",
"price":9222
}
)
print(result)
await es_client_manager.close()
# asyncio.run(test_add_doc())
async def test_add_docs():
operations=[]
goods_list=["小米手机116","小米汽车","华为手机meta80","华为汽车","苹果手机","苹果汽车","苹果iphone"]
for good in goods_list:
operations.append(
{"index":{"_index":index_name}}
)
operations.append(
{
"name":good,
"price":random.randint(1000,9999),
"brand":"小米"
}
)
result = await client.bulk(operations=operations)
print(result)
await es_client_manager.close()
asyncio.run(test_add_docs())
当 ES 和 kibana链接时,Ik_max_word失效问题:
E:\笔记2026项目\项目一_问数\1.docker镜像>docker exec -it elasticsearch /usr/share/elasticsearch/bin/elasticsearch-plugin list
analysis-ik
如果没有 analysis-ik
可以重新安装
测试 有时候 与本地 某些冲突有关
可以用python脚本 测试
或者:
