Last active
April 12, 2019 13:10
-
-
Save Chrstm/f2be484beb34e1475cd7a6f670fa16be to your computer and use it in GitHub Desktop.
How to use array of general datatype in elasticsearch-dsl-py?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from elasticsearch_dsl import DocType, Index, Integer, Text, Q | |
from elasticsearch_dsl.connections import connections | |
import time | |
post_index = Index('test_post') | |
class PostDoc(DocType): | |
author_id = Integer() # List[Integer] | |
tags = Text() # List[Text] | |
uid = Integer() | |
class Index: | |
name = 'test_post' | |
settings = { | |
"number_of_replicas": 2 | |
} | |
@property | |
def id(self): | |
return self.meta.id | |
def search(condition): | |
q = PostDoc.search().query(condition) | |
print("query:", q.to_dict()) | |
results = q.execute() | |
ids = [e.id for e in results] | |
print("result ids =", ids) | |
print() | |
if __name__ == "__main__": | |
connections.create_connection() | |
if post_index.exists(): | |
post_index.delete() | |
PostDoc.init() | |
doc_1 = PostDoc( | |
_id=1, | |
uid=1, | |
author_id=[666, 1, 11, 111], | |
tags=["tech", "information", "make an example"] | |
) | |
doc_1.save() | |
doc_2 = PostDoc( | |
_id=2, | |
uid=2, | |
author_id=[666, 2, 22, 222], | |
tags=["tech", "international", "make a test"] | |
) | |
doc_2.save() | |
time.sleep(1) | |
# query one term | |
search(Q('term', author_id=666)) # 1, 2 | |
search(Q('term', author_id=1)) # 1 | |
search(Q('term', tags="information")) # 1 | |
# query one prefix | |
search(Q('prefix', tags="in")) # 1, 2 | |
search(Q('prefix', tags="te")) # 1, 2 | |
search(Q('prefix', tags="tes")) # 2 | |
# query one word | |
search(Q('match', tags="make")) # 1, 2 | |
search(Q('match', tags="test")) # 2 | |
# query multi doc.meta.id | |
search(Q('ids', values=[2, 3, 4])) # 2 | |
search(Q('ids', values=[3, 4])) # None | |
# query multi terms | |
search(Q('terms', uid=[1, 3])) # 1 | |
search(Q('terms', author_id=[2, 3])) # 2 | |
search(Q('terms', author_id=[1, 3])) # 1 | |
search(Q('terms', author_id=[666, 3])) # 1, 2 | |
search(Q('terms', author_id=[111, 22])) # 1, 2 | |
search(Q('terms', author_id=[1, 222])) # 1, 2 | |
search(Q('terms', author_id=[3, 4, 5])) # None | |
# combine query | |
search((Q('terms', author_id=[3, 4, 5]) | Q('terms', author_id=[1, 2])) & Q('bool', filter=Q('ids', values=[1, 2]))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment