Python中集成es两种方式

Posted Palpitate

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python中集成es两种方式相关的知识,希望对你有一定的参考价值。

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两种方式的主要内容,如果未能解决你的问题,请参考以下文章

使用 chaquopy 在 android studio 中集成 python 代码(对象检测代码)

在 Android 中集成支付选项

eclipse中集成python开发环境

是否可以在网络上的python中集成机器学习算法

如何在 Eclipse 中集成 pep8.py?

30ES集成到项目中