Elasticsearch按数组中的单个嵌套文档键排序

时间:2012-05-02 14:11:25

标签: elasticsearch

我的文档看起来像这样(这里有两个例子):

{
    "id": 1234,
    "title": "the title",
    "body": "the body",
    "examples": [
        {
            "evidence_source": "friend",
            "source_score": 15
        },
        {
            "evidence_source": "parent",
            "source_score": 12
        }
    ]
}

{
    "id": 6346,
    "title": "new title",
    "body": "lots of content",
    "examples": [
        {
            "evidence_source": "friend",
            "source_score": 10
        },
        {
            "evidence_source": "parent",
            "source_score": 27
        },
        {
            "evidence_source": "child",
            "source_score": 4
        }
    ]
}

examples数组中的子文档格式总是有evidence_sourcesource_score,但这些子文档的数量可变,每个子文档都有不同evidence_source值。

我想知道是否可以根据与特定source_score值匹配的evidence_source值之一对此格式的文档进行排序。我真的希望能够做到这一点:

  • source_score降序排列相关evidence_sourcefriend的文档。文档id的结果排序为1234,6346。
  • source_score降序排列相关evidence_sourceparent的文档。文档id的结果排序为6346,1234。

我做出类似这样的事情的最接近的结果是12,但我不相信他们完全符合我想做的事。

关于我如何解决这个问题的任何想法?我已经考虑了一些基于分别索引这些examples子文档的想法,但我对弹性搜索相当新,所以我正在寻找一些关于如何以最直接的方式实现我的目标的建议(可能是一个梦想......)

更新elasticsearch mailing list上的帖子似乎表明这是不可能的,但我想知道这里的其他人是否有任何不同的想法!

1 个答案:

答案 0 :(得分:18)

支持基于嵌套文档内部字段的排序已添加到0.90的弹性搜索:

https://github.com/elasticsearch/elasticsearch/issues/2662

  

嵌套字段支持的排序具有以下参数   现有排序选项的顶部:

     
      
  • nested_path - 定义要排序的嵌套对象。实际上   sort字段必须是此嵌套对象中的直接字段。该   默认是使用最直接的继承嵌套对象   排序领域。
  •   
  • nested_filter - 过滤内部的内部对象   嵌套路径应与其字段值匹配   通过排序考虑。常见的情况是重复查询/   过滤嵌套过滤器或查询内部。默认情况下没有nested_filter   很活跃。
  •   

根据您的示例数据,以下查询应该为您提供您所追求的内容:

{
  "query": {
    "match_all": {}
  },
  "sort": [
    {
      "examples.source_score": {
        "order": "desc",
        "nested_path": "examples",
        "nested_filter": {
          "term": {
            "examples.evidence_source": "friend"
          }
        }
      }
    }
  ]
}
相关问题