如何在弹性搜索中对高度执行范围搜索



如何在 Elasticsearch 中表示 Height 和 HeightRange,以便更容易进行范围搜索

Height.java: int feet, int inches;
HeightRange.java: Height from, Height to

我想搜索落在一定范围内(例如 5 英尺 - 6 英尺)的用户

如果我很好地理解您的问题,您将按如下方式使用范围查询。我按如下方式进行了本地测试,其中我摄取了以下数据:

"hits" : [
{
"_index" : "height-index-array",
"_type" : "_doc",
"_id" : "OfCHdXUB1QlsTOLdRJgd",
"_score" : 1.0,
"_source" : {
"user" : "user1",
"height" : {
"feet" : 5,
"inch" : 8
}
}
},
{
"_index" : "height-index-array",
"_type" : "_doc",
"_id" : "CfCJdXUB1QlsTOLdEZxS",
"_score" : 1.0,
"_source" : {
"user" : "user2",
"height" : {
"feet" : 7,
"inch" : 9
}
}
},
{
"_index" : "height-index-array",
"_type" : "_doc",
"_id" : "CvCJdXUB1QlsTOLdEpx5",
"_score" : 1.0,
"_source" : {
"user" : "user3",
"height" : {
"feet" : 5,
"inch" : 6
}
}
},
{
"_index" : "height-index-array",
"_type" : "_doc",
"_id" : "C_CJdXUB1QlsTOLdE5yk",
"_score" : 1.0,
"_source" : {
"user" : "user4",
"height" : {
"feet" : 5,
"inch" : 8
}
}
},
{
"_index" : "height-index-array",
"_type" : "_doc",
"_id" : "T_CJdXUB1QlsTOLdFZwx",
"_score" : 1.0,
"_source" : {
"user" : "user5",
"height" : {
"feet" : 2,
"inch" : 3
}
}
}
]

我用来查询 5 到 6 之间的heightfeet的查询:

"query": {
"range": {
"height.feet": {
"gte": 5,
"lte": 6
}
}
} 

gte相当于greater than or equal tolte相当于less than or equal to

结果是:

"hits" : {
"total" : {
"value" : 3,
"relation" : "eq"
},
"max_score" : 1.0,
"hits" : [
{
"_index" : "height-index-array",
"_type" : "_doc",
"_id" : "OfCHdXUB1QlsTOLdRJgd",
"_score" : 1.0,
"_source" : {
"user" : "user1",
"height" : {
"feet" : 5,
"inch" : 8
}
}
},
{
"_index" : "height-index-array",
"_type" : "_doc",
"_id" : "CvCJdXUB1QlsTOLdEpx5",
"_score" : 1.0,
"_source" : {
"user" : "user3",
"height" : {
"feet" : 5,
"inch" : 6
}
}
},
{
"_index" : "height-index-array",
"_type" : "_doc",
"_id" : "C_CJdXUB1QlsTOLdE5yk",
"_score" : 1.0,
"_source" : {
"user" : "user4",
"height" : {
"feet" : 5,
"inch" : 8
}
}
}
]
}

如果您有任何问题,请告诉我,我很乐意为您提供帮助:)

根据您的要求,如果您需要组合这两个指标,您可以使用布尔查询:

"query": {
"bool": {
"must": [
{
"range": {
"height.feet": {
"gte": 5,
"lte": 6
}
}
},{
"range": {
"height.inch": {
"gte": 6,
"lte": 8
}
}
}
]
}
}

回应:

"hits" : [
{
"_index" : "height-index-array",
"_type" : "_doc",
"_id" : "OfCHdXUB1QlsTOLdRJgd",
"_score" : 2.0,
"_source" : {
"user" : "user1",
"height" : {
"feet" : 5,
"inch" : 8
}
}
},
{
"_index" : "height-index-array",
"_type" : "_doc",
"_id" : "CvCJdXUB1QlsTOLdEpx5",
"_score" : 2.0,
"_source" : {
"user" : "user3",
"height" : {
"feet" : 5,
"inch" : 6
}
}
},
{
"_index" : "height-index-array",
"_type" : "_doc",
"_id" : "C_CJdXUB1QlsTOLdE5yk",
"_score" : 2.0,
"_source" : {
"user" : "user4",
"height" : {
"feet" : 5,
"inch" : 8
}
}
}
]

链接: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-range-query.html https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html

最新更新