如何在Elasticsearch中为以下内容编写正确的查询
:phoneNumber!= phoneCode +电话
答案 0 :(得分:1)
假设这些字段的类型为text
,并且具有同级的同级keyword
,我共享了一个示例映射,示例文档确认了该映射以及下面的必需查询:
PUT phone
{
"mappings":{
"mydocs":{
"properties":{
"phone":{
"type":"text",
"fields":{
"keyword":{
"type":"keyword",
"ignore_above":256
}
}
},
"phoneCode":{
"type":"text",
"fields":{
"keyword":{
"type":"keyword",
"ignore_above":256
}
}
},
"phoneNumber":{
"type":"text",
"fields":{
"keyword":{
"type":"keyword",
"ignore_above":256
}
}
}
}
}
}
}
POST phone/mydocs/1
{
"phoneNumber": "9654231010",
"phoneCode": "0044",
"phone": "9654231010"
}
POST phone/mydocs/2
{
"phoneNumber": "00449654231010",
"phoneCode": "0044",
"phone": "9654231010"
}
POST phone/_search
{
"query":{
"bool":{
"must":[
{
"script":{
"script":"""
String phoneNumber = doc['phoneNumber.keyword'].value;
String phoneCode = doc['phoneCode.keyword'].value;
String phone = doc['phone.keyword'].value;
if(phoneNumber!=null && phoneCode!=null && phone!=null){
return phoneNumber != phoneCode + phone;
}
"""
}
}
]
}
}
}
我已经在Script Query内使用Bool Query实现了您想要的条件。运行上面的查询,应该只获取具有id:1
现在我还假设phoneNumber
和phoneCode
的值中没有连字符-
或将其用作分隔符,如下面的示例所示>
phoneNumber: 0044-965-423-1010
phoneCode: 0044
phone: 965-423-1010
如果这就是您的值,那么您可能想在脚本中使用contains()
方法,如下所示:
POST phone/_search
{
"query":{
"bool":{
"must":[
{
"script":{
"script":"""
String phoneNumber = doc['phoneNumber.keyword'].value;
String phoneCode = doc['phoneCode.keyword'].value;
String phone = doc['phone.keyword'].value;
if(phoneNumber!=null && phoneCode!=null && phone!=null){
return !(phoneNumber.contains(phoneCode) && phoneNumber.contains(phone));
}
"""
}
}
]
}
}
}
希望这会有所帮助。