码迷,mamicode.com
首页 > 编程语言 > 详细

Python中集成es两种方式

时间:2021-06-16 17:36:10      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:use   delete   rom   missing   date   pymysql   hosts   ali   led   

1、原生集成

# https://github.com/elastic/elasticsearch-py
# https://github.com/elastic/elasticsearch-dsl-py


# Official low-level client for Elasticsearch

### 等同于pymysql
pip3 install elasticsearch
    pip3 install elasticsearch-dsl


from elasticsearch import Elasticsearch

obj = Elasticsearch()   # 得到一个对象
# 创建索引(Index)
# result = obj.indices.create(index=‘user‘, body={"userid":‘1‘,‘username‘:‘lqz‘},ignore=400)
# print(result)
# 删除索引
# result = obj.indices.delete(index=‘user‘, ignore=[400, 404])
# 插入数据
# data = {‘userid‘: ‘1‘, ‘username‘: ‘lqz‘,‘password‘:‘123‘}
# result = obj.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 = obj.update(index=‘news‘, doc_type=‘_doc‘, body=data, id=1)
# print(result)


# 删除数据
# result = obj.delete(index=‘news‘, doc_type=‘_doc‘, id=1)
# print(result)

# 查询
# 查找所有文档
# query = {‘query‘: {‘match_all‘: {}}}
#  查找名字叫做jack的所有文档
query = {query: {match: {title: 十个}}}

# 查找年龄大于11的所有文档
# query = {‘query‘: {‘range‘: {‘age‘: {‘gt‘: 11}}}}

allDoc = obj.search(index=books, doc_type=_doc, body=query)
# print(allDoc)
print(allDoc[hits][hits][0][_source])

2、dsl集成

# Elasticsearch DSL is a high-level

# pip3 install 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(analyzer=ik_max_word)
    author = Text()

    class Index:
        name = myindex

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


if __name__ == __main__:
    # Article.init()  # 创建索引
    # 保存数据
    # article = Article()
    # article.title = "测试测试阿斯顿发送到发斯蒂芬啊啊士大夫阿斯蒂芬"
    # 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()

    #修改数据
    # s = Article().search()
    # s = s.filter(‘match‘, title="测试")
    # results = s.execute()
    # print(results[0])
    # results[0].title="李清照阿斯顿发送到发送阿斯蒂"
    # results[0].save()

 

Python中集成es两种方式

标签:use   delete   rom   missing   date   pymysql   hosts   ali   led   

原文地址:https://www.cnblogs.com/ZhZhang12138/p/14886906.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!