我有一个查询,按给定的时间间隔在文本字段中搜索给定的术语。我想添加短语匹配到这个查询我怎么能添加;例如,我会寻找"has parti"作为一个短语,但文本不应该有"ahmet"这个词。我怎么能做到呢?代码在这里;
{
"query": {
"filtered": {
"filter": {
"bool": {
"must": [
{
"terms": {
"text": [
"has",
"parti"
]
}
},
{
"range": {
"date": {
"gt": "2015-08-27",
"lte": "2015-08-28"
}
}
}
]
}
}
}
}
}
Elasticsearch提供短语匹配,但我不认为你可以在过滤器中使用它,或者至少我没有设法让它工作。我有一个解,match_phrase
在query
中,text
中不含ahmet
,时间间隔保持在filter
中。检查一下它是否适合你。
{
"query": {
"filtered": {
"query": {
"bool": {
"must": [
{
"match_phrase": {
"text": "has parti"
}
}
],
"must_not": [
{
"match": {
"text": "ahmet"
}
}
]
}
},
"filter": {
"bool": {
"must": [
{
"range": {
"date": {
"gt": "2015-08-27",
"lte": "2015-08-28"
}
}
}
]
}
}
}
}
}
顺便说一句,你的date
看起来像被映射为字符串,否则你的请求会失败
ElasticsearchParseException[failed to parse date field [2015-08-22], failed to parse date format [date_time] and timestamp number];nested: IllegalArgumentException[无效格式:"2015-08-22"太短];}]
我建议使用适当的映射,但这与你的问题无关
更新:只是回来补充说,我们做了正确的事情:过滤器不适合全文搜索
更新:由于过滤的查询已被弃用,在新版本中应该重写查询,以便将过滤器移动到bool查询:
{
"query": {
"bool": {
"must": [{
"match_phrase": {
"text": "has parti"
}
}],
"must_not": [{
"match": {
"text": "ahmet"
}
}],
"filter": {
"bool": {
"must": [{
"range": {
"date": {
"gt": "2015-08-27",
"lte": "2015-08-28"
}
}
}]
}
}
}
}
}
您将需要使用短语匹配查询。但是,由于这是一个查询,并且您正在寻找一个过滤器,因此需要将其包装在查询过滤器中。
一旦完成,您应该能够实现短语匹配过滤器。接下来,当您需要一个否定时,将语句放入bool过滤器的must_not中。您也可以使用术语过滤器。
那么最后你的查询应该是这样的-
{
"query": {
"filtered": {
"filter": {
"bool": {
"must_not": [
{
"term": {
"title": "ahmet"
}
}
],
"must": [
{
"range": {
"date": {
"gt": "2015-08-27",
"lte": "2015-08-28"
}
}
},
{
"constantScore": {
"filter": {
"query": {
"match_phrase": {
"title": "has parti"
}
}
}
}
}
]
}
}
}
}
}