Last active
August 29, 2015 14:09
-
-
Save ralphm/6b35b4b175e2a5aaf44b to your computer and use it in GitHub Desktop.
Boolean ES term filter
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
{ | |
"bool": { | |
"must": [ | |
{ | |
"bool": { | |
"should": [ | |
{ | |
"term": { | |
"event": "delivered" | |
} | |
}, | |
{ | |
"term": { | |
"event": "failed" | |
} | |
} | |
] | |
} | |
}, | |
{ | |
"bool": { | |
"must_not": { | |
"term": { | |
"event": "accepted" | |
} | |
} | |
} | |
}, | |
{ | |
"term": { | |
"event": "something" | |
} | |
} | |
] | |
} | |
} |
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
import json | |
import parsley | |
field = 'event' | |
def term(value): | |
return {'term': {field: value}} | |
def unary(operator, operand): | |
return {'bool': {'must_not': operand}} | |
def binary(operator, first, rest): | |
if not rest: | |
return first | |
else: | |
return {'bool': {operator: [first] + rest}} | |
es_query = """ | |
nonSpace = anything:x ?(x not in '( )') -> x | |
term = <nonSpace+>:x ?(x not in ('NOT', 'AND', 'OR')) -> term(x) | |
parens = '(' ws expr:e ws ')' -> e | |
value = ws (term | parens) | |
expr = expr2:first (ws 'OR' expr2)*:rest -> binary('should', first, rest) | |
expr2 = expr3:first (ws 'AND' expr3)*:rest -> binary('must', first, rest) | |
expr3 = ws 'NOT' value:x -> unary('must_not', x) | |
| value | |
""" | |
x = parsley.makeGrammar(es_query, { | |
'term': term, | |
'unary': unary, | |
'binary': binary, | |
}) | |
filterExpr = x("(delivered OR failed) AND NOT accepted AND something").expr() | |
print json.dumps(filterExpr, indent=4) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment