我的问题与此非常相似:Elasticsearch:使用条件过滤器搜索文档 但是,数据结构对我来说有点不同,所以我不能将解决方案用于其他线程。 我有很多文档已编入索引。正如我们所说,有一些限定符告诉我是否需要出示某些文件。这是我的问题开始的时刻。这是例子:
{
locale: en_US,
type: bla,
qualifiers: [
{
criteria: [
{
type: year_range,
lower: 2024,
upper: 2027
},
{
type: ids,
values: [1,20]
}
,
{
type: string_range_term,
lower: "123455",
upper: "zzzzzz"
}
]
},
{
criteria: [
{
type: year_range,
lower: 2010,
upper: 2012
}
]
}
]
}
作为输入,我需要提供所有参数:年份、id、到期日期。 文件需要按以下方式进行匹配:
示例:
如果有任何提示或建议,我将不胜感激,因为我已经为此奋斗了 4 天,但没有取得有希望的结果。我在想是否应该重新组织数据 - 因为这与数据库结构几乎是 1:1 - 它工作得很好......但是,我需要稍微加快文档选择的速度,所以我想将它们移至 ES。 我需要使用其余客户端在 Java 中实现它...但是有了正确的查询,我就能够将其转换为 Java 代码:) 提前谢谢你
您可以使用 elasticsearch 布尔查询 并在 OR 逻辑内部创建一些 AND 逻辑。由于您拥有原始数据,字段类型必须为
nested
。以下是如何使用 must
和 should
子句来做到这一点。
GET search_by_quafilication/_search
{
"query": {
"nested": {
"path": "qualifiers",
"query": {
"bool": {
"should": [ <-- OR logic start
{
"bool": {
"must": [ <-- first AND logic inside of OR
{}
]
}
},
{
"bool": {
"must": [ <-- second AND logic inside of OR
{}
]
}
}
]
}
}
}
}
}
PUT search_by_quafilication
{
"mappings": {
"properties": {
"qualifiers": {
"type": "nested"
}
}
}
}
#check the mapping
GET search_by_quafilication
PUT search_by_quafilication/_doc/1
{
"qualifiers": {
"year": 2011,
"ids": 10,
"string": "aaaa"
}
}
PUT search_by_quafilication/_doc/2
{
"qualifiers": {
"year": 2013,
"ids": 1,
"string": "zzzzzz"
}
}
PUT search_by_quafilication/_doc/3
{
"qualifiers": {
"year": 2025,
"ids": 20,
"string": "zzzzzz"
}
}
PUT search_by_quafilication/_doc/4
{
"qualifiers": {
"year": 2025,
"ids": 50,
"string": "zzzzzz"
}
}
GET search_by_quafilication/_search
{
"query": {
"nested": {
"path": "qualifiers",
"query": {
"bool": {
"should": [
{
"bool": {
"must": [
{
"range": {
"qualifiers.year": {
"gte": 2024,
"lte": 2027
}
}
},
{
"regexp": {
"qualifiers.string": "[A-z]{6}"
}
},
{
"range": {
"qualifiers.ids": {
"gte": 1,
"lte": 20
}
}
}
]
}
},
{
"bool": {
"must": [
{
"range": {
"qualifiers.year": {
"gte": 2010,
"lte": 2012
}
}
}
]
}
}
]
}
}
}
}
}
id:1
和 id:3