我有2个索引,一个存储 users ,另一个存储 articles 。
用户文档:
{
"id" : "152ce52d-e975-4ebd-849a-0a12f535e644",
"email": "bob@email.com",
...
}
索引映射:
{
"mapping": {
"properties": {
"id": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword"
}
}
},
"email": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword"
}
}
}
}
}
}
文章文档:
{
"articleId" : "002ce52d-e975-4ebd-849a-0a12f535a536",
"userId": "152ce52d-e975-4ebd-849a-0a12f535e644",
...
}
索引映射:
{
"mapping": {
"properties": {
"articleId": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword"
}
}
},
"userId": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword"
}
}
}
}
}
}
我正在尝试创建一个多索引查询,该查询返回没有文章的所有用户。
我不知道如何从第二个索引中包含的具有相同id / userId字段的第一项中排除。
假设我有以下用户和文章:
用户:
[
{
"id": "user1",
"email": "bob@email.com"
},
{
"id": "user2",
"email": "john@email.com"
},
{
"id": "user3",
"email": "tom@email.com"
},
{
"id": "user4",
"email": "ben@email.com"
}
]
文章:
[
{
"articleId": "id1",
"userId": "user1"
},
{
"articleId": "id1",
"userId": "user2"
}
]
作为查询的结果,我希望所有没有文章的用户:
[{
"id": "user3",
"email": "tom@email.com"
},
{
"id": "user4",
"email": "ben@email.com"
}]
答案 0 :(得分:1)
正如@leandrojmp指出的那样,您正在尝试实现类似SQL中的JOIN查询的功能,在该查询中您想返回一个索引中的所有其余记录,而这些记录与第二个索引中的记录不匹配。请参阅此文档,以了解有关joining queries in elasticsearch
的更多信息我不知道如何从包含的第一个索引项中排除 在第二个索引中,并且具有相同的id / userId字段。
跨多个索引执行查询时,您可以使用_index field
。
搜索查询:
{
"query": {
"bool": {
"should": [
{
"bool": {
"must_not": [
{
"match": {
"id": "user1"
}
},
{
"match": {
"id": "user2"
}
}
],
"must": {
"term": {
"_index": "64469393user"
}
}
}
},
{
"bool": {
"must_not": [
{
"match": {
"userId": "user1"
}
},
{
"match": {
"userId": "user2"
}
}
],
"must": {
"term": {
"_index": "64469393article"
}
}
}
}
]
}
}
}
搜索结果:
"hits": [
{
"_index": "64469393user",
"_type": "_doc",
"_id": "3",
"_score": 1.0,
"_source": {
"id": "user3",
"email": "tom@email.com"
}
},
{
"_index": "64469393user",
"_type": "_doc",
"_id": "4",
"_score": 1.0,
"_source": {
"id": "user4",
"email": "ben@email.com"
}
}
]