检索仅包含活动用户ID的对象

时间:2018-12-19 23:17:08

标签: arrays object elasticsearch amazon-dynamodb

对于dynamo db和弹性搜索来说还是很新的东西。

所以我有2张桌子。

表1:包含我要显示的项目 表2:包含具有带有布尔值的活动列的用户。 { active: true }

我要做的是检索所有具有active: true的用户ID,然后从表1中检索包含所有这些ID的对象。

第1步:找到活跃用户

let activeUsersResult = await es.search({
      index: userTable, //table2
      body: {
              "query": {
                "bool": {
                  "must": 
                    {
                      "match": { "active": "true" }
                    }

                }
            }
        }
    })

这种工作。我的表包含8个活动用户,但仅检索7个活动用户。我打算联系aws支持人员来解决此问题,但是从SO那里得到一个很好的答案,但这里没有重点。

第2步:获取活动的用户ID

let activeIds = activeUsersResult.hits.hits.map( item => item._source.userId )

这给了我所有活动ID的数组,看起来像:

activeIds = ['id1', 'id2', 'id3', etc....]

第3步:获取仅包含表1中那些activeId的items对象

注意:此es.search还在执行搜索功能

let itemsResult = await es.search({
        index: itemTable, //table 1
        body:{
              "query": {
                "bool": {
                  "must": [
                    {
                        "query_string": {
                            "query": e.searchQuery + "*",
                            "fields": ["item_name"]
                        }
                    },
                    {
                      "match": { "sold_out": "false" },
                      "match": { "userIds" : activeIds }
                    }
                  ]
                }
            }
        }
    })

比赛线是我遇到的问题。 "match": { "userIds" : activeIds }

我需要仅包含那些匹配的activeId的对象数组。我希望将其键入会给我一些想法,但我仍然迷失了。

谢谢!

1 个答案:

答案 0 :(得分:1)

我建议您使用termterms查询而不是匹配。当您需要与数组匹配时,应使用terms查询。因此,您的查询应如下所示。

{
  "query": {
    "bool": {
      "must": [
        {
          "query_string": {
            "query": e.searchQuery + "*",
            "fields": [
              "item_name"
            ]
          }
        },
        {
          "term": {
            "sold_out": "false"
          }
        },
        {
          "terms": {
            "userIds": activeIds
          }
        }
      ]
    }
  }
}

阅读有关termterms查询的信息,以了解有关其工作原理的更多信息。