前言

测试

  • 新建 mapping
PUT my_index
{
  "mappings": {
    "properties": {
      "name": {
        "type": "keyword",
        "doc_values": true,
        "fields": {
          "length": {
            "type": "token_count",
            "analyzer": "standard"
          }
        }
      }
    }
  }
}
  • 写入测试数据
POST my_index/_doc/_1
{"name":  ["A B", "X Y"]}

POST my_index/_doc/2
{"name":  ["A B C", "X Y"]}
  • 查询
GET my_index/_search
{
  "query": {
    "range": {
      "name.length": {
        "gte": 1,
        "lte": 10
      }
    }
  },
  "_source": [
    "*"
  ],
  "script_fields": {
    "token_count": {
      "script": {
        "source": "doc['name.length']",
        "lang": "painless"
      }
    }
  }
}

查询结果如下

{
    "total": {
        "value": 2,
        "relation": "eq"
    },
    "max_score": 1.0,
    "hits": [
        {
            "_index": "my_index",
            "_type": "_doc",
            "_id": "_1",
            "_score": 1.0,
            "_source": {
                "name": [
                    "A B",
                    "X Y"
                ]
            },
            "fields": {
                "token_count": [
                    2,
                    2
                ]
            }
        },
        {
            "_index": "my_index",
            "_type": "_doc",
            "_id": "2",
            "_score": 1.0,
            "_source": {
                "name": [
                    "A B C",
                    "X Y"
                ]
            },
            "fields": {
                "token_count": [
                    2,
                    3
                ]
            }
        }
    ]
}
本文出自 qbit snap

qbit
268 声望279 粉丝