ElasticSearch根据另一个字段上的条件查询字段



映射

PUT /employee
{
"mappings": {
"post": {
"properties": {
"name": {
"type": "keyword"
},
"email_ids": {                    
"properties":{
"id" : { "type" : "integer"},
"value" : { "type" : "keyword"}
}
},
"primary_email_id":{
"type": "integer"
}
}
}
}
}

数据

POST employee/post/1
{
"name": "John",
"email_ids": [
{
"id" : 1,
"value" : "1@email.com"
},
{
"id" : 2,
"value" : "2@email.com"
}
],
"primary_email_id": 2 // Here 2 refers to the id field of email_ids.id (2@email.com).

}

我需要帮助形成一个查询,以检查电子邮件id是否已被用作主电子邮件?

例如:如果我查询1@email.com,我应该得到No的结果,因为1@email.com不是主要的电子邮件id。

如果我查询2@email.com,我应该得到Yes的结果,因为2@email.comJohn的主要电子邮件id。

据我所知,使用此映射无法实现您所期望的。

但是,您可以将email_ids字段创建为nested类型,再添加一个类似isPrimary的字段,并在电子邮件为主电子邮件时将其值设置为true

索引映射

PUT employee
{
"mappings": {
"properties": {
"name": {
"type": "keyword"
},
"email_ids": {
"type": "nested", 
"properties": {
"id": {
"type": "integer"
},
"value": {
"type": "keyword"
},
"isPrimary":{
"type": "boolean"
}
}
},
"primary_email_id": {
"type": "integer"
}
}
}
}

样本文档

POST employee/_doc/1
{
"name": "John",
"email_ids": [
{
"id": 1,
"value": "1@email.com"
},
{
"id": 2,
"value": "2@email.com",
"isPrimary": true
}
],
"primary_email_id": 2
}

查询

您需要保持以下查询的原样,并且只需要在您想查看电子邮件是否为主时更改电子邮件地址。

POST employee/_search
{
"_source": false, 
"query": {
"nested": {
"path": "email_ids",
"query": {
"bool": {
"must": [
{
"term": {
"email_ids.value": {
"value": "2@email.com"
}
}
},
{
"term": {
"email_ids.isPrimary": {
"value": "true"
}
}
}
]
}
}
}
}
}

结果

{
"took" : 2,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 0.98082924,
"hits" : [
{
"_index" : "employee",
"_type" : "_doc",
"_id" : "1",
"_score" : 0.98082924
}
]
}
}

解释结果:

Elasticsearch不会以类似truefalse的布尔值返回结果,但您可以在应用程序级别实现它。可以从结果中考虑hits.total.value的值,若为0,则可以考虑false,否则为true

PS:答案基于ES 7.10版本。

最新更新