如何在根文档中沿边属性投影嵌套文档?

How to project nested documents along side properties in the root document?

我正在尝试 return 嵌套文档的投影以及根文档的一些属性。如果可能的话,我想在查询中执行此操作。

例如,我有一个索引 cities,其中初始数据集:

[
    {
        _id: "1",
        city: "New York"
        state:"NY"
        users: [ 
         {
            firstName: "John",
            lastname: "Peters",
            birthYear: 1985
         }, {
            firstName: "Raul",
            lastname: "Other",
            birthYear: 1986
         }, {
            firstName: "Paul",
            lastname: "Ray",
            birthYear: 1997
         }
        ]       
    },
    {
        _id: "2",
        city: "Hackensack",
        state: "NJ"
        users: [ 
         {
            firstName: "Joe",
            lastname: "Anders",
            birthYear: 1988
         }
        ]
    }, 
    {
        _id: "3",
        city: "Albany"
        state:"NY"
        users: [ 
         {
            firstName: "Zoy",
            lastname: "Bat",
            birthYear: 1984
         }, {
            firstName: "Ana",
            lastname: "Lily",
            birthYear: 1999
         }
        ]        
    }
]

usersnested 类型。 (S/n:我认为这是目前最好的,因为我可能希望过滤其中一个属性,但如果需要我愿意更改它。)

我想查询 NYstate 中由 birthYear 排序的用户,我希望 Elasticsearch 对 return 的查询类似于:

[
  {
    city: "Albany"
    firstName: "Zoy",
    lastname: "Bat",
    birthYear: 1984
  }, {
    city: "New York"
    firstName: "John",
    lastname: "Peters",
    birthYear: 1985
  }, { 
    city: "New York"
    firstName: "Raul",
    lastname: "Other",
    birthYear: 1986
  }, {
    city: "New York"
    firstName: "Paul",
    lastname: "Ray",
    birthYear: 1997
  }, {
    city: "Albany"
    firstName: "Ana",
    lastname: "Lily",
    birthYear: 1999
  }        
]

这感觉在查询期间应该是可能的,但我一直没能找到合适的功能。

使用嵌套文档无法return您所期望的,因为您不能混合和匹配嵌套在不同顶级文档中的文档,并且return它们按照您提到的顺序排列。

您实际上应该非规范化您的数据并且将用户提升为主要实体。首先,这很容易解决您表达的查询需求,其次,我非常有信心这也将支持您的其他需求。

因此您的文档应该如下所示:

 {
    id": 1,
    firstName: "John",
    lastname: "Peters",
    birthYear: 1985,
    city: "New York",
    state:"NY"
 }
 {
    id": 2,
    firstName: "Raul",
    lastname: "Other",
    birthYear: 1986,
    city: "New York",
    state:"NY"
 }
 etc...