一、Python使用
 
from elasticsearch import Elasticsearch
obj = Elasticsearch()
result = obj.indices.create(index='user', body={"userid":'1','username':'lqz'},ignore=400)
'''
不用doc包裹会报错
ActionRequestValidationException[Validation Failed: 1: script or doc is missing
'''
query = {'query': {'match_all': {}}}
allDoc = obj.search(index='news', doc_type='politics', body=query)
print(allDoc['hits']['hits'][0]['_source'])
 
二、Django/Flask集成
 
1、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集成
 
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__':