【问题标题】:ElasticSearch:filtering documents based on field length?ElasticSearch:根据字段长度过滤文档?
【发布时间】:2013-07-28 17:29:13
【问题描述】:

有没有办法根据特定字段的长度过滤 ElasticSearch 文档?

例如,我有一堆带有“body”字段的文档,我只想返回body中字符数> 1000的结果。有没有办法在ES中做到这一点而无需添加索引中包含长度的额外列?

【问题讨论】:

    标签: lucene elasticsearch


    【解决方案1】:

    使用脚本过滤器,像这样:

    "filtered" : {
        "query" : {
            ...
        }, 
        "filter" : {
            "script" : {
                "script" : "doc['body'].length > 1000"
            }
        }
    }
    

    编辑 抱歉,本意是引用the query DSL guide on script filters

    【讨论】:

    • documentation for Elasticsearch 2.1 没有提到 .length 字段,这仍然有效吗?
    • 大概,如果您明确启用脚本支持,这仍然有效(我相信在 v1.4 中默认禁用脚本)。现在使用的是 Groovy 脚本而不是 MVEL,因此您可能需要检查一下。
    • stackoverflow.com/questions/23023233/… 提到您可以使用 "script" : "doc['body'].value.length()" 在 1.7.5 上为我工作
    • 我认为链接不好
    【解决方案2】:

    您还可以创建自定义标记器并在多字段属性中使用它,如下所示:

    PUT test_index
    {
      "settings": {
        "analysis": {
          "analyzer": {
            "character_analyzer": {
              "type": "custom",
              "tokenizer": "character_tokenizer"
            }
          },
          "tokenizer": {
            "character_tokenizer": {
              "type": "nGram",
              "min_gram": 1,
              "max_gram": 1
            }
          }
        }
      }, 
      "mappings": {
        "person": {
          "properties": {
            "name": { 
              "type": "text",
              "fields": {
                "keyword": { 
                  "type": "keyword"
                },
                "words_count": { 
                  "type": "token_count",
                  "analyzer": "standard"
                },
                "length": { 
                  "type": "token_count",
                  "analyzer": "character_analyzer"
                }
              }
            }
          }
        }
      }
    }
    
    PUT test_index/person/1
    {
      "name": "John Smith"
    }
    
    PUT test_index/person/2
    {
      "name": "Rachel Alice Williams"
    }
    
    GET test_index/person/_search
    {
      "query": {
        "term": {
          "name.length": 10
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-19
      • 1970-01-01
      • 1970-01-01
      • 2014-11-17
      • 2021-02-27
      • 2019-08-19
      • 2023-03-04
      相关资源
      最近更新 更多