程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Three ways for Python to operate es

編輯:Python

python operation ES Three ways to

1 Use requests modular

import requests
data = {

"name": " Big lady ",
"age": 18,
"from": "sheng",
"desc": " White and beautiful skin , Charming and lovely ",
"tags": [" white ", " rich ", " beautiful "]
}
res = request.put('http://127.0.0.1:9200/lqz/_doc/6', json=data)
print(res.text)

2 Use official packages

# Recommended elasticsearch We need to pay attention to the version problem 
from elasticsearch import Elasticsearch
client = Elasticsearch("http://localhost:9200")
print(client.info) # es Information 
# Create index 
result = client.indices.create(index='user')
print(result)
# Delete index 
result = client.indices.delete(index='user')
print(result)
# Update data Necessary 
''' no need doc The package will report an error 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)
# Delete data 
result = client.del
print(result)
# Inquire about Inquire about How to check the original , Here you can use it 
# Find all documents 
query = {
'query': {
'match_all': {
}}}
# It's called lxx All documents of 
query = {
'query': {
'term': {
'name': 'lxx'}}}
# Look for ages greater than 11 All documents of 
query = {
'query': {
'range': {
'price': {
'gt': 100}}}}
allDoc = client.search(index='books', body=query)
print(allDoc)

3 ORM package

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' # Index name 
if __name__ == '__main__':
Article.init() # Create mapping 
# Save the data 
article = Article()
article.title = "test"
article.author = "lxx"
article.save() # Save the data 
# Query data 
s=Article.search()
s = s.filter('match', title="test")
results = s.execute()
print(results)
# Delete data 
s = Article.search()
s = s.filter('match', title="test").delete()
# Modifying data 
s = Article().search()
s = s.filter('match', title="test")
results = s.execute()
print(results[0])
results[0].title="xxx"
results[0].save()

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved