在数组对象中搜索 [英] Search within array object
问题描述
我有以下json对象-
I have a the following json object --
{
"Title": "Terminator,
"Purchases": [
{"Country": "US", "Site": "iTunes"},
{"Country": "FR", "Site": "Google"}
]
}
鉴于上述对象,以下是搜索结果显示产量的方式:
Given the above object, here is how the search results show yield:
"Titles on iTunes in US" ==> YES, show "Terminator"
"Titles on Google in FR" ==> YES, show "Terminator"
"Titles on iTunes in FR" ==> NO
但是,如果我只查询AND
,要获得具有Purchase.Country="FR"
的标题和具有Purchase.Site="iTunes"
的标题,则由于同时满足两个条件,因此将错误地显示上述结果.但是,我想将该方面限制为在购买商品之内 . python代码中的等效项是:
However, if I just AND
the query, to get Titles with Purchase.Country="FR"
and Titles with Purchase.Site="iTunes"
, it would erroneously show the above result, since both conditions are met. However, I want to restrict that facet to within the purchase item. The equivalent in python code would be:
for purchase in item['Purchases']:
if purchase['Country'] == "FR" and purchase['Site'] == "iTunes":
return True
当前它是这样的:
for purchase in item['Purchases']:
if purchase['Country'] == "FR":
has_fr = True
if purchase['Site'] == "iTunes":
has_itunes = True
if has_itunes and has_fr: return True
这将在ElasticSearch中完成吗?
How would this be done in ElasticSearch?
推荐答案
首先,您需要通过定义对象类型的映射来将购买"字段索引为嵌套字段:
First, you need to index the "Purchases" field as a nested field, by defining the mapping of your object type like this:
{
"properties" : {
"Purchases" : {
"type" : "nested",
"properties": {
"Country" : {"type": "string" },
"Site" : {"type": "string" }
}
}
}
}
只有那样,ElasticSearch才会保持各个国家和各个站点之间的关联,如
Only then will ElasticSearch keep the association between the individual countries and the individual sites, as described here.
接下来,您应该使用嵌套查询,例如:
Next, you should use a nested query, such as this one:
{ "query":
{ "nested" : {
"path" : "Purchases",
"score_mode" : "avg",
"query" : {
"bool" : {
"must" : [
{
"match" : {"Purchases.Country" : "US"}
},
{
"match" : {"Purchases.Site" : "iTunes"}
}
]
}
}
}
}
}
如果查询结合了"US"和"iTunes",它将返回您的对象,但如果结合了"US"和"Google",则不会返回对象.有关详细信息,请此处 .
This will return your object if the query combines "US" and "iTunes", but not if it combines "US" and "Google". The details are described here.
这篇关于在数组对象中搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!