Lock in $30 Savings on PRO—Offer Ends Soon! ⏳
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Python DSL
Search
Elasticsearch Inc
March 11, 2015
Technology
2
910
Python DSL
Slides for Honza's talk at Elastic{on}
Elasticsearch Inc
March 11, 2015
Tweet
Share
More Decks by Elasticsearch Inc
See All by Elasticsearch Inc
OSCON: Scaling a distributed engineering team from 50-250
elasticsearch
13
1.4k
Stuff a Search Engine Can Do
elasticsearch
17
1.6k
Using Elastic to monitor anything
elasticsearch
3
1.5k
Log all the things!
elasticsearch
4
1.1k
Why Elastic? @ 50th Vinitaly 2016
elasticsearch
5
1.9k
What's New In Elasticland?
elasticsearch
3
880
Kibana, Timelion, Graph Meetup
elasticsearch
3
770
Elastic for Time Series Data and Predictive Analytics
elasticsearch
4
3k
Elastic 2.0
elasticsearch
1
740
Other Decks in Technology
See All in Technology
GDGoC開発体験談 - Gemini生成AI活用ハッカソン / GASとFirebaseで挑むパン屋のフードロス解決 -
hotekagi
1
640
ファインディの4年にわたる技術的負債の返済 / Repaying 4 Years of Technical Debt at Findy
ma3tk
6
3.4k
Ruby on Browser - RubyWorld Conference 2024
tmtms
1
100
「今までで一番学びになった瞬間」発表 LT - Shinjuku.rb #96
kozy4324
0
140
まだチケットを手動で書いてるの?!GitHub Actionsと生成AIでチケットの作成を自動化してみた話 / 20241207 Yoshinori Katayama
shift_evolve
1
210
LangChainとSupabaseを活用して、RAGを実装してみた
atsushii
0
130
2024/12/05 AITuber本著者によるAIキャラクター入門 - AITuberの基礎からソフトウェア設計、失敗談まで
sr2mg4
2
380
[GDG DevFest Bangkok 2024] - The Future of Retail E-commerce with Gemini AI
punsiriboo
0
290
マルチプロダクト、マルチデータ基盤での Looker活用事例 〜BQじゃなくてもLookerはいいぞ〜
gappy50
0
130
高品質と高スピードを両立させるソフトウェアQA/Software QA that Supports Agility and Quality
goyoki
8
1.2k
ミスが許されない領域にAIを溶け込ませる プロダクトマネジメントの裏側
t01062sy
6
6.3k
Kubernetes だけじゃない!Amazon ECS で実現するクラウドネイティブな GitHub Actions セルフホストランナー / CNDW2024
ponkio_o
PRO
6
430
Featured
See All Featured
Why You Should Never Use an ORM
jnunemaker
PRO
54
9.1k
Building Applications with DynamoDB
mza
91
6.1k
Adopting Sorbet at Scale
ufuk
73
9.1k
Building Adaptive Systems
keathley
38
2.3k
Java REST API Framework Comparison - PWX 2021
mraible
PRO
28
8.3k
The Success of Rails: Ensuring Growth for the Next 100 Years
eileencodes
44
6.9k
ReactJS: Keep Simple. Everything can be a component!
pedronauck
665
120k
Making the Leap to Tech Lead
cromwellryan
133
8.9k
Rails Girls Zürich Keynote
gr2m
94
13k
実際に使うSQLの書き方 徹底解説 / pgcon21j-tutorial
soudai
169
50k
Keith and Marios Guide to Fast Websites
keithpitt
410
22k
Faster Mobile Websites
deanohume
305
30k
Transcript
Python DSL Honza Král @honzakral
{ } DSL 2
{ } DSL ? Don't you mean ORM? 3
{ } Current State { "query": { "filtered": { "query":
{ "function_score": { "query": { "bool": { "must": [ {"multi_match": { "fields": ["title^10", "body"], "query": "php"}}, {"has_child": { "child_type": "answer", "query": {"match": {"body": "python"}}}} ], "must_not": [ {"multi_match": { "fields": ["title", "body"], "query": "python"}} ] } }, "field_value_factor": {"field": "rating"} } }, "filter": {"range": {"creation_date": {"from": "2010-01-01"}}} }}, 4 "highlight": { "fields": { "title": {"fragment_size" : 50}, "body": {"fragment_size" : 50} } }, "aggs": { "tags": { "terms": {"field": "tags"}, "aggs": { "comment_avg": { "avg": {"field": "comment_count"} } } }, "frequency": { "date_histogram": { "field": "creation_date", "interval": "month" } } } } JSON DSL
{ } Now add a filter to it! 5
{ } Search Object s = Search(doc_type='question') 6
{ } Simple Query s = s.query('multi_match', fields=['title^10', 'body'], query='php')
7
{ } Compound Query s = s.query('has_child', child_type='answer', query=Q('match', body='python'))
8
{ } Q shortcut {"has_child": { "child_type": "answer', "query": {"match":
{"body": "python"}}}} Q({'has_child': { 'child_type': 'answer', 'query': {'match': {'body': 'python'}}}}) Q('has_child', child_type='answer', query=Q('match', body='python')) HasChild(child_type='answer', query=Match(body='python')) 9
{ } Query expressions Q(...) & Q(...) == Bool(must=[Q(...), Q(...)])
Q(...) | Q(...) == Bool(should=[Q(...), Q(...)]) ~Q(...) == Bool(must_not=[Q(..)]) 10
{ } Filter s = s.filter('range', creation_date={'from': date(2010, 1, 1)})
11
{ } Exclude s = s.query(~Q('multi_match', fields=['title^10', 'body'], query='python')) 12
{ } Manual query s.query = Q('function_score', query=s.query, field_value_factor={'field': 'rating'})
13
{ } Aggregations s.aggs.bucket('tags', 'terms', field='tags')\ .metric('comment_avg', 'avg', field='comment_count') s.aggs.bucket('frequency',
'date_histogram', field='creation_date', interval='month') 14
{ } Highlight ... s = s.highlight('title', 'body', fragment_size=50) 15
{ } Migration path s = Search.from_dict(my_glorious_query) s = s.filter('term',
tag='published') my_glorious_query = s.to_dict() 16 query at a time
{ } Response response = s.execute() for hit in response:
print(hit.meta.score, hit.title) for tag in response.aggregations.tags.buckets: print(tag.key, tag.avg_comments.value) 17 No more brackets!
{ } Persistence From Mapping to Model-like DocTypes 18
{ } Mapping DSL m = Mapping('article') m.field('published_from', Date()) m.field('title',
String(fields={'raw': String(index='not_analyzed')})) m.field('comments', Nested()) m['comments'].property('author', String()) m.save('index-name') m.update_from_es('index-name') 19
{ } DocType class Article(DocType): title = String() created_date =
Date() comments = Nested(properties={'author': String()}) class Meta: index = 'blog' def save(self, **kwargs): self.created_date = now() super().save(**kwargs) Article.init() Article.search()... Search(doc_type=Article) 20
{ } Configuration 21
{ } Connections connections.configure( default={'hosts': ['localhost'], 'sniff_on_start': True}, logging={ 'hosts':
['log1:9200', 'log2:9200'], 'timeout': 30, 'sniff_timeout': 120}) Search(using='logging') es = connections.get_connection() es.indices.delete(index='_all') 22
{ } Future 23
{ } More DSLs! Index Analyzers Settings ... 24
{ } FacetedSearch ? class MySiteSearch(FacetedSearch): doc_type = [Article, Comment]
fields = ['title', 'body'] published = DateHistogram( interval='week', field='published_date') category = Term(field='category') 25 Definition ???
{ } FacetedSearch ? s = MySiteSearch('python', category='blog') for hit
in s: print(h.meta.score, h.title) cat_facet = s.facets['category'] for name, count in cat_facet: mask = '%s: %d' if name == cat_facet.selected: mask = '<b>%s: %d</b>' print(mask % (name, count)) 26 Usage ????
{ } Django integration ? Model -> DocType signal handlers
to update management command to sync FacetedSearch -> Form view + template pattern 27
{ } Thank you! @honzakral
{ } This work is licensed under the Creative Commons
Attribution-NoDerivatives 4.0 International License. To view a copy of this license, visit: http://creativecommons.org/licenses/by-nd/4.0/ or send a letter to: Creative Commons PO Box 1866 Mountain View, CA 94042 USA CC-BY-ND 4.0 29