python操作Elasticsearch

python操作Elasticsearch

1. elaticsearch:官方提供的,类似于原生操作,pymysql
	https://github.com/elastic/elasticsearch-py
    
2. elaticsearch-dsl:高级库,类似于orm,django的orm一样

elaticsearch

# pip3 install elasticsearch==7.0.5
from elasticsearch import Elasticsearch
"""
纯用requests模块,也可以实现
import requests
res=requests.put("http://localhost:9200/lqz5")
print(res)
"""

client=Elasticsearch("http://localhost:9200")
# 创建索引(Index)
 result = client.indices.create(index='user',ignore=400)
 print(result)

# 删除索引
 result = client.indices.delete(index='lqz3')
 print(result)


# 插入数据
'''
PUT news/_doc/1
{
  "userid":"1",
  "username":lqz,
  "password":"123",
}
'''
# 把mysql的数据,同步到es中--》pymsql打开查询---》直接存到es中
data = {'userid': '1', 'username': 'lqz','password':'123'}
result = client.create(index='news', doc_type='_doc', id=1, body=data)
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.delete(index='news', doc_type='_doc', id=1)
print(result)

# 查询
# 查找所有文档
query = {'query': {'match_all': {}}}
allDoc = client.search(index='t1',body=query)
print(allDoc)

# 查询title带有中国的文档
query = {'query': {'match': {'title': '中国'}}}
allDoc = client.search(index='t1',body=query)

# 查找年龄大于11的所有文档
query = {'query': {'range': {'age': {'gt': 11}}}}
allDoc = client.search(index='t1',body=query)
print(allDoc)
  

elasticsearch_dsl

# elaticsearch-dsl:高级库,类似于orm,django的orm一样
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(analyzer='ik_max_word', search_analyzer="ik_max_word", fields={'title': Keyword()})
    author = Keyword()

    class Index:
        name = 'myindex'

    # def save(self, **kwargs):
    #     return super(Article, self).save(**kwargs)


if __name__ == '__main__':
    # Article.init()  # 创建映射
# 保存数据
#     article = Article()
#     article.title = "python测试开发岗位"
#     article.author = "lqz"
#     article.save()  # 数据就保存了

    # 查询数据
    # s=Article.search()
    # s = s.filter('match', title="开发")
    # results = s.execute()
    # print(results[0].title)

    # 删除数据
    # s = Article.search()
    # s = s.filter('match', title="开发").delete()
    # print(s)

    # 修改数据
    s = Article().search()
    s = s.filter('match', title="测试")
    results = s.execute()
    print(results[0])
    results[0].title="测试开发"
    results[0].save()

posted @ 2022-03-15 16:18  yang_night  阅读(480)  评论(0)    收藏  举报