python操作ES的三种办法
1 使用requests模块
import requests
data = {
"name": "大娘子",
"age": 18,
"from": "sheng",
"desc": "肤白貌美,娇憨可爱",
"tags": ["白", "富", "美"]
}
res = request.put('http://127.0.0.1:9200/lqz/_doc/6', json=data)
print(res.text)
2 使用官方提供的包
# 推荐使用 elasticsearch 需要注意版本问题
from elasticsearch import Elasticsearch
client = Elasticsearch("http://localhost:9200")
print(client.info) # es信息
# 创建索引
result = client.indices.create(index='user')
print(result)
# 删除索引
result = client.indices.delete(index='user')
print(result)
# 更新数据 必须的用
'''
不用doc包裹会报错
ActionRequestValidationException[Validation Failed: 1: script or doc is missing
'''
data = {'doc': {'userid': '1', 'username': 'lqz', 'password': '123ee', 'test': 'test'}}
result = client.update(index='news', doc_type='_doc', body=data, id=1)
print(result)
# 删除数据
result = client.del
print(result)
# 查询 查询 原生咋查,这里就可以咋用
# 查找所有文档
query = {'query': {'match_all': {}}}
# 查找名字叫做lxx的所有文档
query = {'query': {'term': {'name': 'lxx'}}}
# 查找年龄大于11的所有文档
query = {'query': {'range': {'price': {'gt': 100}}}}
allDoc = client.search(index='books', body=query)
print(allDoc)
3 ORM包
elasticsearch-dsl
from datetime import datetime
from elasticsearch_dsl import Document, Date, Nested, Boolean,analyzer, InnerDoc, Completion, Keyword, Text,Integer
from elasticsearch_dsl.connections import connections
connections.create_connection(hosts=["localhost"])
class Article(Document):
title = Text(fields={'title': Keyword()})
author = Text()
class Index:
name = 'myindex' # 索引名
if __name__ == '__main__':
Article.init() # 创建映射
# 保存数据
article = Article()
article.title = "test"
article.author = "lxx"
article.save() # 保存数据
# 查询数据
s=Article.search()
s = s.filter('match', title="test")
results = s.execute()
print(results)
# 删除数据
s = Article.search()
s = s.filter('match', title="test").delete()
# 修改数据
s = Article().search()
s = s.filter('match', title="test")
results = s.execute()
print(results[0])
results[0].title="xxx"
results[0].save()
文章来源地址https://www.toymoban.com/news/detail-517397.html
文章来源:https://www.toymoban.com/news/detail-517397.html
到了这里,关于python操作ES的三种办法的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!