Elasticsearch Reference
  • Introduction
  • 入门
    • 基本概念
    • 安装
    • 探索集群
      • 集群健康
      • 获取所有索引库
      • 创建一个索引库
      • 索引文档创建与查询
      • 删除索引
    • 修改数据
      • 更新文档
      • 删除文档
      • 批量处理
    • 探索您的数据
      • 搜索API
      • 查询语言介绍
      • 执行搜索
      • 执行过滤
      • 执行聚合
    • 总结
  • Elasticsearch设置
    • 安装Elasticsearch
      • .zip或.tar.gz文件的安装方式
      • Debian软件包安装方式
      • RPM安装方式
      • Windows安装方式
      • Docker安装方式
    • 配置Elasticsearch
    • 重要的Elasticsearch配置
    • 安全配置
    • 启动前检查
      • 堆大小检查
      • 文件描述符检查
      • 内存锁定检查
      • 最大线程数检查
      • 最大虚拟内存检查
      • 最大map数检查
      • JVM检查
      • 串行收集使用检查
      • 系统调用过滤检查
      • OnError与OnOutOfMemroyError检查
      • G1GC检查
    • 重要的系统配置
      • 系统设置
      • 在jvm.options中设置JVM堆大小
      • 禁用swapping
      • 文件描述符
      • 虚拟内存
      • 线程数
    • Elasticsearch升级
      • 滚动升级
      • 全集群重启升级
      • 索引重建升级
    • Elasticsearch停机
  • 重大变更
    • 5.3重大变更
    • 5.2重大变更
      • 删除Shadow副本
    • 5.1重大变更
    • 5.0重大变更
      • 搜索与查询DSL变化
      • Mapping变化
      • Percolator变化
      • Suggester变化
      • Index API变化
      • Document API变化
      • Settings变化
      • Allocation变化
      • HTTP变化
      • REST API变化
      • CAT API变化
      • JAVA API变化
      • 安装包
      • 插件变化
      • 文件系统相关变化
      • 磁盘数据文件路径
      • Aggregation变化
      • 脚本相关变化
  • API约定
    • 多索引语法
    • 索引库名称的日期运算
    • 常用选项
    • URL-based访问控制
  • 文档API
    • 读写文档
    • Index API
    • Get API
    • Delete API
    • Delete By Query API
    • Update API
    • Update By Query API
    • Multi Get API
    • Bulk API
    • Reindex API
    • Term Vectors
    • Multi termvectors API
    • refresh
  • 搜索API
    • Search
    • URI Search
    • Request Body Search
      • Query
      • From / Size
      • Sort
      • Source filtering
      • Fields
      • Script Fields
      • Doc value Fields
      • Post filter
      • Highlighting
      • Rescoring
      • Search Type
      • Scroll
      • Preference
      • Explain
      • Version
      • Index Boost
      • min_score
      • Named Queries
      • Inner hits
      • Field Collapsing
      • Search After
    • Search Template
    • Multi Search Template
    • Search Shards API
    • Suggesters
      • Term suggester
      • Phrase Suggester
      • Completion Suggester
      • Context Suggester
    • Multi Search API
    • Count API
    • Validate API
    • Explain API
    • Profile API
      • Profiling Queries
      • Profiling Aggregations
      • Profiling Considerations
    • Percolator
    • Field stats API
  • 聚合
    • Metrics Aggregations
      • Avg Aggregation
      • Cardinality Aggregation
      • Extended Stats Aggregation
      • Geo Bounds Aggregation
      • Geo Centroid Aggregation
      • Max Aggregation
      • Min Aggregation
      • Percentiles Aggregation
      • Percentile Ranks Aggregation
      • Scripted Metric Aggregation
      • Stats Aggregation
      • Sum Aggregation
      • Top hits Aggregation
      • Value Count Aggregation
    • Bucket Aggregations
      • Adjacency Matrix Aggregation
      • Children Aggregation
      • Date Histogram Aggregation
      • Date Range Aggregation
      • Diversified Sampler Aggregation
      • Filter Aggregation
      • Filters Aggregation
      • Geo Distance Aggregation
      • GeoHash grid Aggregation
      • Global Aggregation
      • Histogram Aggregation
      • IP Range Aggregation
      • Missing Aggregation
      • Nested Aggregation
      • Range Aggregation
      • Reverse nested Aggregation
      • Sampler Aggregation
      • Significant Terms Aggregation
      • Terms Aggregation
    • Pipeline Aggregations
      • Avg Bucket Aggregation
      • Derivative Aggregation
      • Max Bucket Aggregation
      • Min Bucket Aggregation
      • Sum Bucket Aggregation
      • Stats Bucket Aggregation
      • Extended Stats Bucket Aggregation
      • Percentiles Bucket Aggregation
      • Moving Average Aggregation
      • Cumulative Sum Aggregation
      • Bucket Script Aggregation
      • Bucket Selector Aggregation
      • Serial Differencing Aggregation
    • Matrix Aggregations
      • Matrix Stats
    • Caching heavy aggregations
    • Returning only aggregation results
    • Aggregation Metadata
  • 索引库API
    • Create Index
    • Delete Index
    • Get Index
    • Indices Exists
    • Open / Close Index API
    • Shrink Index
    • Rollover Index
    • Put Mapping
    • Get Mapping
    • Get Field Mapping
    • Types Exists
    • Index Aliases
    • Update Indices Settings
    • Get Settings
    • Analyze
      • Explain Analyze
    • Index Templates
    • Shadow replica indices
      • Node level settings related to shadow replicas
    • Indices Stats
    • Indices Segments
    • Indices Recovery
    • Indices Shard Stores
    • Clear Cache
    • Flush
      • Synced Flush
    • Refresh
    • Force Merge
  • cat API
    • cat aliases
    • cat allocation
    • cat count
    • cat fielddata
    • cat health
    • cat indices
    • cat master
    • cat nodeattrs
    • cat nodes
    • cat pending tasks
    • cat plugins
    • cat recovery
    • cat repositories
    • cat thread pool
    • cat shards
    • cat segments
    • cat snapshots
    • cat templates
  • 集群API
    • Cluster Health
    • Cluster State
    • Cluster Stats
    • Pending cluster tasks
    • Cluster Reroute
    • Cluster Update Settings
    • Nodes Stats
    • Nodes Info
    • Task Management API
    • Nodes hot_threads
    • Cluster Allocation Explain API
  • DSL查询
    • Query and filter context
    • Match All Query
    • Full text queries
      • Match Query
      • Match Phrase Query
      • Match Phrase Prefix Query
      • Multi Match Query
      • Common Terms Query
      • Query String Query
      • Simple Query String Query
    • Term level queries
      • Term Query
      • Terms Query
      • Range Query
      • Exists Query
      • Prefix Query
      • Wildcard Query
      • Regexp Query
      • Fuzzy Query
      • Type Query
      • Ids Query
    • Compound queries
      • Constant Score Query
      • Bool Query
      • Dis Max Query
      • Function Score Query
      • Boosting Query
      • Indices Query
    • Joining queries
      • Nested Query
      • Has Child Query
      • Has Parent Query
      • Parent Id Query
    • Geo queries
      • GeoShape Query
      • Geo Bounding Box Query
      • Geo Distance Query
      • Geo Distance Range Query
      • Geo Polygon Query
    • Specialized queries
      • More Like This Query
      • Template Query
      • Script Query
      • Percolate Query
    • Span queries
      • Span Term Query
      • Span Multi Term Query
      • Span First Query
      • Span Near Query
      • Span Or Query
      • Span Not Query
      • Span Containing Query
      • Span Within Query
      • Span Field Masking Query
    • Minimum Should Match
    • Multi Term Query Rewrite
  • Mapping
    • Field datatypes
      • Array datatype
      • Binary datatype
      • Range datatypes
      • Boolean datatype
      • Date datatype
      • Geo-point datatype
      • Geo-Shape datatype
      • IP datatype
      • Keyword datatype
      • Nested datatype
      • Numeric datatypes
      • Object datatype
      • String datatype
      • Text datatype
      • Token count datatype
      • Percolator type
    • Meta-Fields
      • _all field
      • _field_names field
      • _id field
      • _index field
      • _meta field
      • _parent field
      • _routing field
      • _source field
      • _type field
      • _uid field
    • Mapping parameters
      • analyzer
      • normalizer
      • boost
      • coerce
      • copy_to
      • doc_values
      • dynamic
      • enabled
      • fielddata
      • format
      • ignore_above
      • ignore_malformed
      • include_in_all
      • index
      • index_options
      • fields
      • norms
      • null_value
      • position_increment_gap
      • properties
      • search_analyzer
      • similarity
      • store
      • term_vector
    • Dynamic Mapping
      • default mapping
      • Dynamic field mapping
      • Dynamic templates
      • Override default template
  • Analysis
    • Anatomy of an analyzer
    • Testing analyzers
    • Analyzers
      • Configuring built-in analyzers
      • Standard Analyzer
      • Simple Analyzer
      • Whitespace Analyzer
      • Stop Analyzer
      • Keyword Analyzer
      • Pattern Analyzer
      • Language Analyzers
      • Fingerprint Analyzer
      • Custom Analyzer
      • Normalizers
    • Tokenizers
      • Standard Tokenizer
      • Letter Tokenizer
      • Lowercase Tokenizer
      • Whitespace Tokenizer
      • UAX URL Email Tokenizer
      • Classic Tokenizer
      • Thai Tokenizer
      • NGram Tokenizer
      • Edge NGram Tokenizer
      • Keyword Tokenizer
      • Pattern Tokenizer
      • Path Hierarchy Tokenizer
    • Token Filters
      • Standard Token Filter
      • ASCII Folding Token Filter
      • Flatten Graph Token Filter
      • Length Token Filter
      • Lowercase Token Filter
      • Uppercase Token Filter
      • NGram Token Filter
      • Edge NGram Token Filter
      • Porter Stem Token Filter
      • Shingle Token Filter
      • Stop Token Filter
      • Word Delimiter Token Filter
      • Stemmer Token Filter
      • Stemmer Override Token Filter
      • Keyword Marker Token Filter
      • Keyword Repeat Token Filter
      • KStem Token Filter
      • Snowball Token Filter
      • Phonetic Token Filter
      • Synonym Token Filter
      • Synonym Graph Token Filter
      • Compound Word Token Filter
      • Reverse Token Filter
      • Elision Token Filter
      • Truncate Token Filter
      • Unique Token Filter
      • Pattern Capture Token Filter
      • Pattern Replace Token Filter
      • Trim Token Filter
      • Limit Token Count Token Filter
      • Hunspell Token Filter
      • Common Grams Token Filter
      • Normalization Token Filter
      • CJK Width Token Filter
      • CJK Bigram Token Filter
      • Delimited Payload Token Filter
      • Keep Words Token Filter
      • Keep Types Token Filter
      • Classic Token Filter
      • Apostrophe Token Filter
      • Decimal Digit Token Filter
      • Fingerprint Token Filter
      • Minhash Token Filter
    • Character Filters
      • HTML Strip Char Filter
      • Mapping Char Filter
      • Pattern Replace Char Filter
  • 模块
    • 集群
      • 集群的分片分配
      • 基于磁盘的分片分配
      • 了解分片分配
      • 分片分配过滤
      • 其他群集设置
    • Discovery
      • Azure Classic Discovery
      • EC2 Discovery
      • Google Compute Engine Discovery
      • Zen Discovery
    • 本地网关
    • HTTP
    • 索引库
      • 熔断
      • Fielddata
      • 节点查询缓存
      • 索引缓冲
      • 分片请求缓存
      • 索引库恢复
    • 网络设置
    • 节点
    • 插件
    • 脚本
      • 如何使用脚本
      • 文档中字段的访问以及一些特殊变量
      • 脚本与安全
      • Groovy脚本语言
      • PainLess脚本语言
      • PainLess语法
      • PainLess调试
      • Lucene表达式语言
      • 原生(java)脚本
      • 高级文本评分脚本
    • 快照与还原
    • 线程池
    • 传输
    • Tribe节点
    • 跨集群搜索
  • Index模块
    • Analysis
    • Index Shard Allocation
      • Shard Allocation Filtering
      • Delaying allocation when a node leaves
      • Index recovery prioritization
      • Total Shards Per Node
    • Mapper
    • Merge
    • Similarity module
    • Slow Log
    • Store
      • Pre-loading data into the file system cache
    • Translog
  • Ingest节点
    • Pipeline Definition
    • Ingest APIs
      • Put Pipeline API
      • Get Pipeline API
      • Delete Pipeline API
      • Simulate Pipeline API
    • Accessing Data in Pipelines
    • Handling Failures in Pipelines
    • Processors
      • Append Processor
      • Convert Processor
      • Date Processor
      • Date Index Name Processor
      • Fail Processor
      • Foreach Processor
      • Grok Processor
      • Gsub Processor
      • Join Processor
      • JSON Processor
      • KV Processor
      • Lowercase Processor
      • Remove Processor
      • Rename Processor
      • Script Processor
      • Set Processor
      • Split Processor
      • Sort Processor
      • Trim Processor
      • Uppercase Processor
      • Dot Expander Processor
  • How To
    • General recommendations
    • Recipes
    • Tune for indexing speed
    • Tune for search speed
    • Tune for disk usage
  • Testing
    • Java Testing Framework
      • why randomized testing?
      • Using the elasticsearch test classes
      • unit tests
      • integration tests
      • Randomized testing
      • Assertions
  • 术语表
  • 发布说明
    • 5.3.0 Release Notes
    • 5.2.2 Release Notes
    • 5.2.1 Release Notes
    • 5.2.0 Release Notes
    • 5.1.2 Release Notes
    • 5.1.1 Release Notes
    • 5.1.0 Release Notes
    • 5.0.2 Release Notes
    • 5.0.1 Release Notes
    • 5.0.0 Combined Release Notes
    • 5.0.0 GA Release Notes
    • 5.0.0-rc1 Release Notes
    • 5.0.0-beta1 Release Notes
    • 5.0.0-alpha5 Release Notes
    • 5.0.0-alpha4 Release Notes
    • 5.0.0-alpha3 Release Notes
    • 5.0.0-alpha2 Release Notes
    • 5.0.0-alpha1 Release Notes
    • 5.0.0-alpha1 Release Notes (Changes previously released in 2.x)
  • Painless API参考文档
Powered by GitBook
On this page
  • 更多的模板案例
  • 使用单个值填充查询字符串
  • 将参数转换为 JSON
  • 连接数组的值
  • 默认值
  • 条件语句
  • URL编码
  • 预注册(Pre-registered)模板
  • 验证(Validating)模板
  • Explain
  • Profiling

Was this helpful?

  1. 搜索API

Search Template

PreviousSearch AfterNextMulti Search Template

Last updated 4 years ago

Was this helpful?

/_search/template端点允许使用mustache语言在执行前预渲染搜索请求,并使用模板参数填充现有模板。

GET /_search/template
{
    "inline" : {
      "query": { "match" : { "{{my_field}}" : "{{my_value}}" } },
      "size" : "{{my_size}}"
    },
    "params" : {
        "my_field" : "foo",
        "my_value" : "bar",
        "my_size" : 5
    }
}

关于Mustache templating以及你可以使用哪种模板,请参考 。

注意:

mustache语言在elasticsearch中作为沙盒脚本语言实现,因此对于启用或禁用,源代码和操作等设置,它遵从的描述。

更多的模板案例

使用单个值填充查询字符串

GET /_search/template
{
    "inline": {
        "query": {
            "match": {
                "title": "{{query_string}}"
            }
        }
    },
    "params": {
        "query_string": "search for these words"
    }
}

将参数转换为 JSON

{{#toJson}}parameter{{/toJson}}函数可以用来转换参数(比如maps和array)为它们的JSON形式。

GET /_search/template
{
  "inline": "{ \"query\": { \"terms\": { \"status\": {{#toJson}}status{{/toJson}} }}}",
  "params": {
    "status": [ "pending", "published" ]
  }
}

其呈现为:

{
  "query": {
    "terms": {
      "status": [
        "pending",
        "published"
      ]
    }
  }
}

更复杂的例子代替一个 JSON 对象数组:

{
    "inline": "{\"query\":{\"bool\":{\"must\": {{#toJson}}clauses{{/toJson}} }}}",
    "params": {
        "clauses": [
            { "term": "foo" },
            { "term": "bar" }
        ]
   }
}

呈现为:

{
    "query" : {
      "bool" : {
        "must" : [
          {
            "term" : "foo"
          },
          {
            "term" : "bar"
          }
        ]
      }
    }
}

连接数组的值

{{#join}}array{{/join}}函数能用来将数组的值连接为以逗号分隔的字符串:

GET /_search/template
{
  "inline": {
    "query": {
      "match": {
        "emails": "{{#join}}emails{{/join}}"
      }
    }
  },
  "params": {
    "emails": [ "username@email.com", "lastname@email.com" ]
  }
}

其呈现为:

{
    "query" : {
        "match" : {
            "emails" : "username@email.com,lastname@email.com"
        }
    }
}

该函数还可以接受一个自定义分隔符:

GET /_search/template
{
  "inline": {
    "query": {
      "range": {
        "born": {
            "gte"   : "{{date.min}}",
            "lte"   : "{{date.max}}",
            "format": "{{#join delimiter='||'}}date.formats{{/join delimiter='||'}}"
            }
      }
    }
  },
  "params": {
    "date": {
        "min": "2016",
        "max": "31/12/2017",
        "formats": ["dd/MM/yyyy", "yyyy"]
    }
  }
}

呈现为:

{
    "query" : {
      "range" : {
        "born" : {
          "gte" : "2016",
          "lte" : "31/12/2017",
          "format" : "dd/MM/yyyy||yyyy"
        }
      }
    }
}

默认值

默认值被写成{{var}}{{^var}}default{{/var}}比如:

{
  "inline": {
    "query": {
      "range": {
        "line_no": {
          "gte": "{{start}}",
          "lte": "{{end}}{{^end}}20{{/end}}"
        }
      }
    }
  },
  "params": { ... }
}

此时params是 { "start": 10, "end": 15 },该查询可以呈现为:

{
    "range": {
        "line_no": {
            "gte": "10",
            "lte": "15"
        }
  }
}

但是,params是{ "start": 10 }时, 该查询就会使用默认值作为end:

{
    "range": {
        "line_no": {
            "gte": "10",
            "lte": "20"
        }
    }
}

条件语句

条件语句不能使用模板的 JSON 形式表示。相反,模板必须作为字符串传递。例如,假设我们想在line字段上运行match查询,并且可以选择用行号过滤其中start和end是可选的。

参数(params)会像这样:

{
    "params": {
        "text": "words to search for",
        "line_no": {    # ①
            "start": 10, # ②
            "end": 20   # ③
        }
    }
}

①、②、③ 所有这三个元素都是可选的。

查询语句我们可以是:

{
  "query": {
    "bool": {
      "must": {
        "match": {
          "line": "{{text}}" # ①
        }
      },
      "filter": {
        {{#line_no}}  # ②
          "range": {
            "line_no": {
              {{#start}}  # ③
                "gte": "{{start}}" # ④
                {{#end}},{{/end}} # ⑤
              {{/start}} # ⑥
              {{#end}} # ⑦
                "lte": "{{end}}" # ⑧
              {{/end}} # ⑨
            }
          }
        {{/line_no}} # ⑩
      }
    }
  }
}

① 填充text参数值。

② 仅当指定line_no时才能包含range过滤器。

③ 仅当指定了line_no.start时才能包含gte子句。

④ 填充line_no.start参数值。

⑤ 仅当line_no.start和line_no.end被指定时,在gte子句后添加逗号。

⑦⑨ 仅当指定line_no.end时,包含lte子句。

⑩ 填充 line_no.end 参数值。

注意:

{
  "inline": "{\"query\":{\"bool\":{\"must\":{\"match\":{\"line\":\"{{text}}\"}},\"filter\":{{{#line_no}}\"range\":{\"line_no\":{{{#start}}\"gte\":\"{{start}}\"{{#end}},{{/end}}{{/start}}{{#end}}\"lte\":\"{{end}}\"{{/end}}}}{{/line_no}}}}}}"
}

URL编码

作为一个例子,编码一个URL是很有用的:

GET _render/template
{
    "inline" : {
        "query" : {
            "term": {
                "http_access_log": "{{#url}}{{host}}/{{page}}{{/url}}"
            }
        }
    },
    "params": {
        "host": "https://www.elastic.co/",
        "page": "learn"
    }
}

前面的查询将呈现为:

{
    "template_output" : {
        "query" : {
            "term" : {
                "http_access_log" : "https%3A%2F%2Fwww.elastic.co%2F%2Flearn"
            }
        }
    }
}

预注册(Pre-registered)模板

你可以通过将搜索模板存储在config/scripts目录中,在使用 .mustache扩展名的文件中注册搜索模板。为了执行存储的模板,请使用template键下的名称来引用它:

GET /_search/template
{
    "file": "storedTemplate",  # ①
    "params": {
        "query_string": "search for these words"
    }
}

① config/sripts/查询模板的名称,即:storedTemplate.mustache。

你还可以通过将搜索模板存储在集群状态中来注册搜索模板,由REST API来管理这些索引的模板。

POST /_search/template/<templatename>
{
    "template": {
        "query": {
            "match": {
                "title": "{{query_string}}"
            }
        }
    }
}

该模板可以通过以下方法来检查:

GET /_search/template/<templatename>

其可以呈现为:

{
    "template": {
        "query": {
            "match": {
                "title": "{{query_string}}"
            }
        }
    }
}

这个模板可以被删除:

DELETE /_search/template/<templatename>

在搜索时使用索引模板,使用:

GET /_search/template
{
    "id": "templateName",  # ①
    "params": {
        "query_string": "search for these words"
    }
}

① 存储在 .scripts 索引中的查询模板的名称。

验证(Validating)模板

可以在具有给定参数的响应中使用来呈现模板:

GET /_render/template
{
  "inline": {
    "query": {
      "terms": {
        "status": [
          "{{#status}}",
          "{{.}}",
          "{{/status}}"
        ]
      }
    }
  },
  "params": {
    "status": [ "pending", "published" ]
  }
}

此次调用将返回呈现的模板:

{
  "template_output": {
    "query": {
      "terms": {
        "status": [  # ①
          "pending",
          "published"
        ]
      }
    }
  }
}

① status 数据已使用来自 params 对象的值填充。

文件和索引模板也可以通过分别用file或id代替inline来呈现。例如,呈现文件模板:

GET /_render/template
{
  "file": "my_template",
  "params": {
    "status": [ "pending", "published" ]
  }
}

预注册模板可以使用以下呈现:

GET /_render/template/<template_name>
{
  "params": {
    "..."
  }
}

Explain

你可以在运行模板时使用Explain参数:

GET _search/template
{
  "file": "my_template",
  "params": {
    "status": [ "pending", "published" ]
  },
  "explain": true
}

Profiling

你可以在运行模板时使用Profiling参数:

GET _search/template
{
  "file": "my_template",
  "params": {
    "status": [ "pending", "published" ]
  },
  "profile": true
}

如上所述,模板不是有效的JSON 形式,因为它包含类似{{line_no}}的部分标记,因此,模板应存储在文件中(参考一节)或者在通过REST API使用时,应该将其写成字符串格式,比如:

可以使用{{#url}}value{{/ url}}函数按中定义的HTML编码格式对字符串值进行编码。

HTML规范
预注册模板
mustache项目在线文档
脚本文档