首頁 > 軟體

Elasticsearches之python使用及Django與Flask整合範例

2022-04-19 22:00:03

Elasticsearch之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'])

Elasticsearch之Django/Flask整合

elasticsearch-dsl

#安裝: 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)

django整合

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()

以上就是Elasticsearches之python使用及Django與Flask整合範例的詳細內容,更多關於python Elasticsearches之Django與Flask整合的資料請關注it145.com其它相關文章!


IT145.com E-mail:sddin#qq.com