You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Elasticsearch如何按固定格式_id的末尾数字规则搜索文档

Elasticsearch: Match _id by Position-Based Digit Patterns

Got it, let's break down how to solve this since your Elasticsearch _id is a fixed-length string (starting with ACC plus padded zeros/digits) and you need to match specific digit patterns at the end (or any position) of that ID.

First, note that your _id is likely stored as a keyword type (which is default for _id), so we can use wildcard or regexp queries directly without worrying about text tokenization. If for some reason it's mapped as text, use _id.keyword instead in all the queries below.

Scenario 1: Last digit is 9 (format: xxxxxxx9)

For simple suffix matches, a wildcard query is quick and easy. If you want stricter pattern validation, use a regexp query.

Wildcard Query

{
  "query": {
    "wildcard": {
      "_id": "*9"
    }
  }
}

Regexp Query (more precise)

{
  "query": {
    "regexp": {
      "_id": ".+9$"
    }
  }
}

The $ anchor ensures the match is at the very end, and .+ matches all preceding characters.

Scenario 2: Second-last digit is 3, last digit is 0-5 (format: xxxxxx3[0-5])

Wildcard queries don't support range matches, so regexp is the way to go here.

{
  "query": {
    "regexp": {
      "_id": ".+3[0-5]$"
    }
  }
}
  • 3 matches the second-last digit exactly
  • [0-5] matches any digit from 0 to 5 for the last position
  • $ anchors the pattern to the end of the ID

Scenario 3: Third-last digit is 3-8, last digit is 4 (format: xxxxxx[3-8]x4)

Again, regexp gives us the flexibility to target specific positions regardless of what's in between.

{
  "query": {
    "regexp": {
      "_id": ".+[3-8].4$"
    }
  }
}
  • [3-8] matches any digit from 3 to 8 in the third-last position
  • . matches any single character (digit, in your case) in the second-last position
  • 4$ ensures the last digit is 4

General Approach for Any Position-Based Match

Since your _id has a fixed length, you can make your regexp queries even more efficient by being explicit about the length instead of using .+. For example, if your full _id length is 15 characters (3 for ACC + 12 digits), you could rewrite Scenario 3's regexp as:

ACC\d{9}[3-8]\d4$

This avoids the generic .+ and directly targets the exact positions, which can speed up query performance.


内容的提问来源于stack exchange,提问作者Waku-2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:57:51