Crafting elasticsearch queries in Python.
Creating JSON-like structures in Python (or any other programming language), can be a cumbersome experience. Consider this snippet from the elasticsearch-py library, taken from the example/query.py file:
I would argue that 33 lines for creating the facets above is too much.
To save you from the dreaded hassle of writing JSON in your programs, I created addict, a Python dictionary that let’s you create nested dictionaries using get- and set attribute syntax.
Here’s how the same code looks with addict:
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 addict import Dict | |
body = Dict() | |
body.size = 0 | |
body.query.filtered.filter.has_parent.type = 'repos' | |
body.query.filtered.query.filtered.filter.term.tags = 'python' | |
body.facets.committers.terms_stats = {'key_field': 'committer.name.raw', | |
'value_field': 'stats.lines'} | |
result = es.search(index='git', doc_type='commits', body=body) |
addict is open-source and MIT-licensed. It is actively developed and anyone interested is encouraged to submit issues and pull requests, as both are more than welcome.