filtering facets in elasticsearch

 ̄綄美尐妖づ 提交于 2019-12-05 03:49:56

问题


I have a query like below,

    query = {

        "query": {"query_string": {"query": "%s" % q}},
        "filter":{"ids":{"values":list(ids)}},
        "facets": {"destination": {
            "terms": {"field": "destination.en"}},
        "hotel_class":{
            "terms":{"field":"hotel_class"}},
        "hotel_type":{
            "terms":{"field": "hotel_type"}},
        }}

But my facets are not filtered due to my ids filter. I get all the facets, but I want them filtered by my ids filter above. Do you have any ideas ?


回答1:


Although what you do works, a cleaner solution would be to have a filtered query. http://www.elasticsearch.org/guide/reference/query-dsl/filtered-query/

Which allows for your original query + some arbitrary filter (which in turn can be a complex boolean/ nested filter, etc.)

  {
    query: {
        "filtered" : {
           "query": {"query_string": {"query": "%s" % q}},
           "filter":{"ids":{"values":list(ids)}},
        }
    },
    "facets": {
        "destination": {
            "terms": {"field": "destination.en"}
        },
        "hotel_class": {
            "terms": {"field": "hotel_class"}
        },
        "hotel_type": {
            "terms": {"field": "hotel_type"}
        }
    }
 }

The rationale is the following:

  • any query is applied BEFORE faceting.
  • any filter is applied AFTER faceting.

So if you want your facets to be filtered by some filter, you have to include said filter in the QUERY.




回答2:


facet_filter fixed my problem,

like below,

{
  "query": {
    "query_string": {
      "query": "%s" %q
    }
  },
  "filter": {
    "ids": {
      "values": list(ids)
    }
  },
  "facets": {
    "destination": {
      "terms": {
        "field": "destination.en"
      },
      "facet_filter": {
        "ids": {
          "values": list(ids)
        }
      }
    },
    "hotel_class": {
      "terms": {
        "field": "hotel_class"
      },
      "facet_filter": {
        "ids": {
          "values": list(ids)
        }
      }
    },
    "hotel_type": {
      "terms": {
        "field": "hotel_type"
      },
      "facet_filter": {
        "ids": {
          "values": list(ids)
        }
      }
    },
  }
}


来源:https://stackoverflow.com/questions/16231727/filtering-facets-in-elasticsearch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!