当前位置 : 主页 > 编程语言 > python >

python操作elasticsearch

来源:互联网 收集:自由互联 发布时间:2022-06-20
from elasticsearch import Elasticsearch # 删除索引 def delete_indices ( es , my_index ): if es . indices . exists ( my_index ): # 确认删除再改为True es . indices . delete ( index = my_index ) # 删除 # 创建索引示例1 def cr
from elasticsearch import Elasticsearch

# 删除索引
def delete_indices(es, my_index):
if es.indices.exists(my_index): # 确认删除再改为True
es.indices.delete(index=my_index) # 删除

# 创建索引示例1
def create_indices(es, my_index):
# 创建
es.indices.create(index=my_index)

# 查询索引内容
def search_index(es, my_index):
body = {
"query":{
"match":{
"name":"jgc"
}
}
}
res = es.search(index=my_index, body=body)
# res = es.search(index=my_index, body=body, filter_path=['hits.hits']
return res

if __name__ == "__main__":
# 链接数据库
es = Elasticsearch(['http://127.0.0.1:9200'])

# 测试是否能链接
print(es.ping())

# 创建索引
create_indices(es, "newlab")

# 删除索引
delete_indices(es, "newlab")

# 查询
print(search_index(es, "lab"))
for item in res['hits']['hits']:
print(item['_source'])from elasticsearch import Elasticsearch

# 删除索引
def delete_indices(es, my_index):
if es.indices.exists(my_index): # 确认删除再改为True
es.indices.delete(index=my_index) # 删除

# 创建索引
def create_indices(es, my_index):
mappings = {
"mappings":{
"properties": {
"name": {
"type": "text"
},
"age": {
"type": "integer"
}
}
}
}
# 创建索引时添加限制
es.indices.create(index=my_index, body=mappings)

# 插入一条数据
def insert_index(es, my_index):
body = {
"name":"smr",
"age":10
}
# 也可以在body里添加"_id"指定id,默认id为随机值
es.index(index=my_index, body=body)

# 查询索引内容
def search_index(es, my_index):
body = {
"query":{
"match_all":{
}
}
}
res = es.search(index=my_index, body=body)
# res = es.search(index=my_index, body=body, filter_path=['hits.hits']
return res

if __name__ == "__main__":
# 链接数据库
es = Elasticsearch(['http://127.0.0.1:9200'])

# 测试是否能链接
# print(es.ping())

# 创建索引
# create_indices(es, "test")

# 插入一条数据
# insert_index(es, "test")

# 查询
print(search_index(es, "test"))
# for item in res['hits']['hits']:
# print(item['_source'])


上一篇:anaconda、python、pycharm区别
下一篇:没有了
网友评论