Вопрос

I am using Elasticsearch to index documents that have an owner which is stored in a userId property of the source object. I can easily do a facet on the userId and get facets for each owner that there is, but I'd like to have the facets for owner show up like so:

  • Documents owned by me (X)
  • Documents owned by others (Y)

I could handle this on the client side and take all of the facets returned by elasticsearch and go through them and figure out those owned by the current user and not and display it appropriately, but I was hoping there was a way to tell elasticsearch to handle this in the query itself.

Это было полезно?

Решение

You can use filtered facets to do this:

curl -XGET "http://localhost:9200/_search" -d'
{
  "query": {
    "match_all": {}
  },
  "facets": {
    "my_docs": {
      "filter": {
        "term": { "user_id": "my_user_id" }
      }
    },
    "others_docs": {
      "filter": {
        "not": {
          "term": { "user_id": "my_user_id" }
        }
      }
    }
  }
}'

One of the nice things about this is that the two terms filters are identical and so are only executed once. The not filter just inverts the results of the cached term filter.

Другие советы

You're right, ElasticSearch has a way to do that. Take a look to scripting term facets, specially to the second example ("using the boolean feature"). You should be able to do somthing like:

{
    "query" : {
        "match_all" : {  }
    },
    "facets" : {
        "userId" : {
            "terms" : {
                "field" : "userId",
                "size" : 10,
                "script" : "term == '<your user id>' ? true : false"
            }
        }
    }
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top