【发布时间】:2014-05-25 00:43:11
【问题描述】:
我是 ElasticSearch 的新手,正在努力学习它。
在常规 RDBM 中,我可以执行如下“in”语句:
select * from results where mycal in ['abc', 'def', 'ghi'] and col2 in ['er', 'es', 'et']
如何在弹性搜索中做到这一点?
谢谢
【问题讨论】:
标签: elasticsearch
我是 ElasticSearch 的新手,正在努力学习它。
在常规 RDBM 中,我可以执行如下“in”语句:
select * from results where mycal in ['abc', 'def', 'ghi'] and col2 in ['er', 'es', 'et']
如何在弹性搜索中做到这一点?
谢谢
【问题讨论】:
标签: elasticsearch
很大程度上取决于您如何在 elasticsearch 中索引数据。但是您可以使用terms filter 来实现上述目的:
{
"filter": {
"and": [
{
"terms": {
"cal": [
"abc",
"def",
"ghi"
],
"execution": "or"
}
},
{
"terms": {
"col2": [
"er",
"es",
"et"
],
"execution": "or"
}
}
]
}
}
【讨论】:
根据您是否想要filter or a query,您可以使用bool 查询/过滤器或快捷方式terms 查询/过滤器(两者都链接到查询,因为我预计这不会是缓存)。
当您要处理多个字段时,您希望在其中使用 bool 查询:
{
"query" : {
"bool" : {
"should" : [
{ "terms" : { "mycal" : [ "abc", "def", "ghi" ] } },
{ "terms" : { "col2" : [ "er", "es", "et" ] } }
],
"minimum_should_match" : 2
}
}
}
默认情况下,"minimum_should_match" 将为1,这将使上述查询成为OR。
这假设文件如下:
{ "mycal" : "abc", "col2" : "es" }
{ "mycal" : "def", "col2" : "er" }
如果您的字段嵌套在一个对象中(例如,{ "key" : { "mycal" : "abc" } }),那么您只需像 "key.mycal" 一样访问它们。
重要的部分是您如何进行映射。默认情况下,您的字符串将全部小写进行分析和存储,因此您需要使用全部小写的term(s) 查询进行搜索。如果您想找到"ABC",那么您仍然会寻找"abc"。但是,如果您使用其他内容,例如 match 而不是 term(s),则无需将其全部小写:
{
"query" : {
"bool" : {
"should" : [
{ "match" : { "mycal" : "ABC" } },
{ "match" : { "mycal" : "DEF" } },
{ "match" : { "mycal" : "GHI" } },
{ "match" : { "col2" : "ER" } },
{ "match" : { "col2" : "ES" } },
{ "match" : { "col2" : "ET" } }
],
"minimum_should_match" : 2
}
}
}
【讨论】: