Skip to content

Instantly share code, notes, and snippets.

@ijharulislam
Last active July 30, 2017 16:43
Show Gist options
  • Select an option

  • Save ijharulislam/bade809123c0efe73bc7e5f17f662799 to your computer and use it in GitHub Desktop.

Select an option

Save ijharulislam/bade809123c0efe73bc7e5f17f662799 to your computer and use it in GitHub Desktop.
from elasticsearch_dsl import Search, Q, query as dslq
from app import es
targetings = [
{
"field": "country",
"operator": "NOT IN",
"value": "BD"
},
{
"field": "offer_id",
"operator": "=",
"value": 1234
},
{
"field": "platform",
"operator": "=",
"value": "iOS"
}
]
s = Search(using=es, index="users")
s.extra(size=volume)
logical_operator_mappings = {
'IN': 'must',
'NOT IN': 'must_not',
'AND': 'must',
'OR': 'should',
'=': 'filter'
}
q = Q()
for query in targetings:
bool_q = Q('bool',
**{logical_operator_mappings.get(
query.get('operator')
): Q('term', **{query["field"]: query["value"]})})
q += bool_q
s = s.query(q)
s.query = dslq.FunctionScore(
query=s.query,
functions=[dslq.SF('random_score')],
boost_mode="replace"
)
res = s.execute()
subscribers = []
for row in res.hits:
subscriber = row.to_dict()
subscriber['_id'] = row.meta.id
subscribers.append(subscriber)
return subscribers
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment