Elasticsearch单词计数查询过滤器



我目前正在寻找一种方法来返回某个字段中最多n个单词的文档。

对于包含"name"字段中少于三个单词的文档的结果集,查询可能是这样的,但据我所知,没有什么比word_count更好的了。

有人知道如何处理这件事吗,甚至可能用不同的方式?

GET myindex/myobject/_search
{
  "query": {
    "filtered": {
      "filter": {
        "bool": {
          "must": [
            {
              "word_count": {
                "name": {
                  "lte": 3
                }
              }
            }
          ]
        }
      },
      "query": {
        "match_all" : { }
      }
    }
  }
}

您可以使用token_count数据类型来索引给定字段中的令牌数量,然后在该字段上进行搜索。

# 1. create the index/mapping with a token_count field
PUT myindex
{
  "mappings": {
    "myobject": {
      "properties": {
        "name": { 
          "type": "string",
          "fields": {
            "word_count": { 
              "type":     "token_count",
              "analyzer": "standard"
            }
          }
        }
      }
    }
  }
}
# 2. index some documents
PUT index/myobject/1
{
   "name": "The quick brown fox"
}
PUT index/myobject/2
{
   "name": "brown fox"
}
# 3. the following query will only return document 2
POST myindex/_search
{
  "query": {
    "range": {
      "name.word_count": { 
        "lt": 3  
      }
    }
  }
}

最新更新