Facet to get all keys from an object in elasticsearch

こ雲淡風輕ζ 提交于 2019-12-11 02:14:28

问题


Let's say I have the following docs:

{
    "title": "Some Title",
    options: {
        "key5": 1,
        "key3": 0,
        "key1": 1,
    }
},
{
    "title": "Some Title",
    options: {
        "key2": 0,
        "key3": 0,
        "key5": 1,
    }
}

I want to get all the keys from options object using facet.

If options was a simple array of keys as strings, I would simple use a facet like this:

"facets" : {
    "options" : {
        "terms" : {
            "field" : "options"
        }
    }
}

But it doesn't work in my case.

So if a query returns those two docs, I should get these keys: ["key5","key3","key1","key2"]

What kind of facet do I actually need?


回答1:


You can't do that using a facet. You have 2 options -

  1. Keep your current document structure and get the list of keys from the type mapping (see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-get-mapping.html). This brings the scheme of your type which holds all the fields encountered.

  2. Change your structure. Keep the key also as a field, so your option array becomes an array of documents like:

    "options" :
    [
    { "key" : "key1", "value" : 1},
    { "key" : "key2", "value" : 0}
    ]

You probably will want to keep the context of the key-value pairs when searching or faceting so configure it as a nested type (http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/mapping-nested-type.html). Then you can facet on the "options.key" field to get a list of top keys.




回答2:


if i understand you correctly, you would want to make a terms_facet for each and every field in your nested options object. kind of a "wildcard facet"?

i think that there is no functionality in the facet api that allows for this kind of operation. if i am not mistaken, fields used for faceting have to be mapped, so it might be possible to extract the fields in a separate query by inspecting the index mappings.



来源:https://stackoverflow.com/questions/19479786/facet-to-get-all-keys-from-an-object-in-elasticsearch

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