'Build ES query for feed.
Must match region.
Orders by FeedItem.order.
Boosted operator shelf matching region + carrier.
Boosted operator shelf matching original_region + carrier.
region -- region ID (integer)
carrier -- carrier ID (integer)
original_region -- region from before we were falling back,
to keep the original shelf atop the RoW feed.'

def get_es_feed_query(self, sq, region=mkt.regions.RESTOFWORLD.id, carrier=None, original_region=None):

    region_filter = es_filter.Term(region=region)
    shelf_filter = es_filter.Term(item_type=feed.FEED_TYPE_SHELF)
    ordering_fn = es_function.FieldValueFactor(field='order', modifier='reciprocal', filter=es_filter.Bool(must=[region_filter], must_not=[shelf_filter]))
    boost_fn = es_function.BoostFactor(value=10000.0, filter=shelf_filter)
    if (carrier is None):
        return sq.query('function_score', functions=[ordering_fn], filter=es_filter.Bool(must=[region_filter], must_not=[shelf_filter]))
    region_filters = [region_filter]
    if original_region:
        region_filters.append(es_filter.Term(region=original_region))
    return sq.query('function_score', functions=[boost_fn, ordering_fn], filter=es_filter.Bool(should=region_filters, must_not=[es_filter.Bool(must=[shelf_filter], must_not=[es_filter.Term(carrier=carrier)])]))
