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
  • 排序值
  • 排列顺序
  • 排列模式选项
  • 排序模式用法示例
  • 使用内嵌对象排序
  • 内嵌对象排序示例
  • 缺失值
  • 忽略没有映射的字段
  • GEO距离排序
  • 属性格式的经纬度
  • 字符串格式的经纬度
  • GeoHash
  • 经纬度数组
  • 多个引用点
  • 基于脚本排序
  • 追踪分数
  • 内存注意事项

Was this helpful?

  1. 搜索API
  2. Request Body Search

Sort

允许在特定字段上添加一个或多个排序。 每个排序也可以颠倒。 排序是在每个字段级别上定义的,具有_score的特殊字段名称按分数排序,_doc按索引顺序排序。

假设以下索引映射:

PUT /my_index
{
    "mappings": {
        "my_type": {
            "properties": {
                "post_date": { "type": "date" },
                "user": {
                    "type": "keyword"
                },
                "name": {
                    "type": "keyword"
                },
                "age": { "type": "integer" }
            }
        }
    }
}
GET /my_index/my_type/_search
{
    "sort" : [
        { "post_date" : {"order" : "asc"}},
        "user",
        { "name" : "desc" },
        { "age" : "desc" },
        "_score"
    ],
    "query" : {
        "term" : { "user" : "kimchy" }
    }
}

注意:

排序值

返回的每个文档的排序值也作为响应的一部分返回。

排列顺序

排序选项可以有以下值:

选项

描述

asc

升序

desc

降序

在对_score进行排序时,该顺序默认为desc,在对其他事物进行排序时默认为asc。

排列模式选项

Elasticsearch支持按数组或多值字段排序。mode选项控制选择用于对其所属文档进行排序的数组值。 mode选项可以具有以下值:

选项

描述

min

选择最低值。

max

选择最高值。

sum

使用所有值的和作为排序值。 仅适用于基于数字的数组字段。

avg

使用所有值的平均值作为排序值。 仅适用于基于数字的数组字段。

median

使用所有值的中值作为排序值。 仅适用于基于数字的数组字段。

排序模式用法示例

在下面的示例中,每个文档字段价格有多个价格。 在这种情况下,结果匹配将按基于每个文档的平均价格的升序排序。

PUT /my_index/my_type/1?refresh
{
   "product": "chocolate",
   "price": [20, 4]
}

POST /_search
{
   "query" : {
      "term" : { "product" : "chocolate" }
   },
   "sort" : [
      {"price" : {"order" : "asc", "mode" : "avg"}}
   ]
}

使用内嵌对象排序

Elasticsearch 还支持根据一个或多个嵌套对象内的字段进行排序。 通过嵌套字段支持进行的排序在已经存在的排序选项之上具有以下参数:

nested_path

定义要排序的嵌套对象。 实际排序字段必须是此嵌套对象内的直接字段。 当通过嵌套字段排序时,此字段是必需的。

nested_filter

嵌套路径中的内部对象应与其匹配的过滤器,以便通过排序考虑其字段值。 常见的情况是在嵌套的过滤器或查询中重复查询/过滤。 默认情况下,没有 nested_filter 是激活的。

内嵌对象排序示例

在下面的示例中,offer是一个类型为嵌套的字段。 需要指定nested_path; 否则,elasticsearch不知道需要捕获哪个嵌套级排序值。

POST /_search
{
   "query" : {
      "term" : { "product" : "chocolate" }
   },
   "sort" : [
       {
          "offer.price" : {
             "mode" :  "avg",
             "order" : "asc",
             "nested_path" : "offer",
             "nested_filter" : {
                "term" : { "offer.color" : "blue" }
             }
          }
       }
    ]
}

内嵌对象排序同样也支持脚本排序和按地理距离排序。

缺失值

missing参数指定如何处理缺少此字段的文档:missing的值可以设置为_last,_first或自定义值(将用于缺失字段的文档的排序值)。

例如:

GET /_search
{
    "sort" : [
        { "price" : {"missing" : "_last"} }
    ],
    "query" : {
        "term" : { "product" : "chocolate" }
    }
}

注意

如果嵌套的内部对象与nested_filter不匹配,则使用缺少的值。

忽略没有映射的字段

默认地,如果没有与字段关联的映射,搜索请求将失败。 unmapped_type选项允许忽略没有映射且没有由它们排序的字段。 此参数的值用于确定要发出的排序值。下面是一个如何使用它的例子:

GET /_search
{
    "sort" : [
        { "price" : {"unmapped_type" : "long"} }
    ],
    "query" : {
        "term" : { "product" : "chocolate" }
    }
}

如果查询的任何索引没有price的映射,那么Elasticsearch将处理它,就好像存在类型为long的映射,其中该索引中的所有文档都没有该字段的值。

GEO距离排序

允许按_geo_distance排序。 下面是一个例子,假设pin.location是一个类型为geo_point的字段:

GET /_search
{
    "sort" : [
        {
            "_geo_distance" : {
                "pin.location" : [-70, 40],
                "order" : "asc",
                "unit" : "km",
                "mode" : "min",
                "distance_type" : "arc"
            }
        }
    ],
    "query" : {
        "term" : { "user" : "kimchy" }
    }
}

distance_type

如何计算距离。 如何计算距离。可以是弧(默认)或平面(更快,但长距离不准确,靠近极点)。

mode

如果字段有多个地理点,该怎么办。 默认情况下,按升序排序时考虑最短距离,按降序排序时最长距离。 支持的值为 min,max,median 和 avg。

unit

计算排序值时使用的单位。 默认值为 m(米)。

注意

geo distance sorting不支持可配置的缺失值:当文档没有用于距离计算的字段的值时,距离将始终被视为等于Infinity。

在提供坐标时支持以下格式:

属性格式的经纬度

GET /_search
{
    "sort" : [
        {
            "_geo_distance" : {
                "pin.location" : {
                    "lat" : 40,
                    "lon" : -70
                },
                "order" : "asc",
                "unit" : "km"
            }
        }
    ],
    "query" : {
        "term" : { "user" : "kimchy" }
    }
}

字符串格式的经纬度

在lat,lon中的格式。

GET /_search
{
    "sort" : [
        {
            "_geo_distance" : {
                "pin.location" : "40,-70",
                "order" : "asc",
                "unit" : "km"
            }
        }
    ],
    "query" : {
        "term" : { "user" : "kimchy" }
    }
}

GeoHash

GET /_search
{
    "sort" : [
        {
            "_geo_distance" : {
                "pin.location" : "drm3btev3e86",
                "order" : "asc",
                "unit" : "km"
            }
        }
    ],
    "query" : {
        "term" : { "user" : "kimchy" }
    }
}

经纬度数组

GET /_search
{
    "sort" : [
        {
            "_geo_distance" : {
                "pin.location" : [-70, 40],
                "order" : "asc",
                "unit" : "km"
            }
        }
    ],
    "query" : {
        "term" : { "user" : "kimchy" }
    }
}

多个引用点

多个地理点可以作为一个包含任何 geo_point 格式的数组传递,例如,

GET /_search
{
    "sort" : [
        {
            "_geo_distance" : {
                "pin.location" : [[-70, 40], [-71, 42]],
                "order" : "asc",
                "unit" : "km"
            }
        }
    ],
    "query" : {
        "term" : { "user" : "kimchy" }
    }
}

等等。

文档的最终距离将是包含在文档中的所有点的最小/最大/平均(通过模式定义)到在排序请求中给出的所有点的距离。

基于脚本排序

允许基于自定义脚本排序,这里是一个例子:

GET /_search
{
    "query" : {
        "term" : { "user" : "kimchy" }
    },
    "sort" : {
        "_script" : {
            "type" : "number",
            "script" : {
                "lang": "painless",
                "inline": "doc['field_name'].value * params.factor",
                "params" : {
                    "factor" : 1.1
                }
            },
            "order" : "asc"
        }
    }
}

追踪分数

在字段上排序时,不会计算分数。 通过将track_scores设置为true,仍将计算和跟踪分数。

GET /_search
{
    "track_scores": true,
    "sort" : [
        { "post_date" : {"order" : "desc"} },
        { "name" : "desc" },
        { "age" : "desc" }
    ],
    "query" : {
        "term" : { "user" : "kimchy" }
    }
}

内存注意事项

排序时,相关的排序字段值将加载到内存中。这意味着每个分片应该有足够的内存来容纳它们。对于基于字符串的类型,排序的字段不应该被analyzed或tokenized。对于数字类型,如果可能,建议将类型显式设置为较窄类型(如short,integer和float)。

PreviousFrom / SizeNextSource filtering

Last updated 4 years ago

Was this helpful?

_doc除了能最有效率的排列顺序、没有真正的使用场景。所以如果你不关心文档返回的顺序,那么你应该按_doc排序。 这特别有助于。

格式是[lon,lat],注意,lon/lat的顺序在这里为了符合。

滚动
GeoJSON