Elasticsearch--Python使用、Django/Flask集成

一、Python使用

python 复制代码
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='politics', 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='politics', body=data, id=1)
# print(result)


# 删除数据
# result = obj.delete(index='news', doc_type='politics', id=1)

# 查询
# 查找所有文档
query = {'query': {'match_all': {}}}
#  查找名字叫做jack的所有文档
# query = {'query': {'term': {'username': 'lqz'}}}

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

allDoc = obj.search(index='news', doc_type='politics', body=query)
print(allDoc['hits']['hits'][0]['_source'])

二、Django/Flask集成

1、elasticsearch-dsl

python 复制代码
#安装: pip3 install elasticsearch-dsl
#示例
from datetime import datetime
from elasticsearch_dsl import Document, Date, Nested, Boolean, \
    analyzer, InnerDoc, Completion, Keyword, Text

html_strip = analyzer('html_strip',
    tokenizer="standard",
    filter=["standard", "lowercase", "stop", "snowball"],
    char_filter=["html_strip"]
)

class Comment(InnerDoc):
    author = Text(fields={'raw': Keyword()})
    content = Text(analyzer='snowball')
    created_at = Date()

    def age(self):
        return datetime.now() - self.created_at

class Post(Document):
    title = Text()
    title_suggest = Completion()
    created_at = Date()
    published = Boolean()
    category = Text(
        analyzer=html_strip,
        fields={'raw': Keyword()}
    )

    comments = Nested(Comment)

    class Index:
        name = 'blog'

    def add_comment(self, author, content):
        self.comments.append(
          Comment(author=author, content=content, created_at=datetime.now()))

    def save(self, ** kwargs):
        self.created_at = datetime.now()
        return super().save(** kwargs)

2、django集成

python 复制代码
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 = 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.save()  # 数据就保存了

    #查询数据
    # s=Article.search()
    # s = s.filter('match', title="测试")
    #
    # results = s.execute()
    # print(results)

    #删除数据
    # 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="xxx"
    # results[0].save()
相关推荐
不惑_17 分钟前
【Python入门第七讲】列表(List)
开发语言·python·list
雪的期许18 分钟前
Python/GoLang/Java 多环境管理工具 pyenv/goenv/jenv
开发语言·python·策略模式
2401_8906661335 分钟前
(免费送源码)计算机毕业设计原创定制:Java+JSP+HTML+JQUERY+AJAX+MySQL springboot计算机类专业考研学习网站管理系统
java·python·django·flask·node.js·html·课程设计
XWM_Web1 小时前
JavaApi---第二节
java·开发语言·python·学习
Zaly.1 小时前
【Python刷题】动态规划相关问题
开发语言·python·动态规划
只怕自己不够好1 小时前
《全面解析图像平滑处理:多种滤波方法及应用实例》
图像处理·python·opencv
股票GPT分析2 小时前
《Python 股票交易分析:开启智能投资新时代》(一)
服务器·开发语言·python·fastapi
天才奇男子2 小时前
Python爬虫爬取网页小说
开发语言·爬虫·python
努力更新中2 小时前
Python浪漫之画明亮的月亮
开发语言·python·动画
数据小爬虫@2 小时前
利用Python爬虫获取商品评论:技术与实践
开发语言·爬虫·python