diff --git a/i18n/TRANSLATION-GUIDE.md b/i18n/TRANSLATION-GUIDE.md index 7143057f..b1ec88ee 100644 --- a/i18n/TRANSLATION-GUIDE.md +++ b/i18n/TRANSLATION-GUIDE.md @@ -13,6 +13,12 @@ 1. 读者是中文开发者和运维人员。译文要自然、通顺,不要逐词硬译;使用简体中文。 2. **术语**:OpenSearch 核心术语首次出现时写成「中文(English)」,之后只用中文。例如:索引(Index)、文档(Document)、字段(Field)、映射(Mapping)、分片(Shard)、主分片(Primary Shard)、副本分片(Replica Shard)、节点(Node)、集群(Cluster)、集群管理节点(Cluster Manager Node)、分析器(Analyzer)、分词器(Tokenizer)、词元过滤器(Token Filter)、聚合(Aggregation)、桶聚合(Bucket Aggregation)、指标聚合(Metric Aggregation)、查询(Query)、过滤器(Filter)、相关性评分(Relevance Score)、摄取管道(Ingest Pipeline)、处理器(Processor)、搜索管道(Search Pipeline)、快照(Snapshot)、别名(Alias)、索引模板(Index Template)、索引状态管理(Index State Management,ISM)、段(Segment)、段复制(Segment Replication)、远程存储(Remote Store)、跨集群复制(Cross-cluster Replication)、可观测性(Observability)、向量搜索(Vector Search)、神经搜索(Neural Search)、混合搜索(Hybrid Search)。 其他已统一的译法:插件(plugin)、仪表板(dashboard,产品名 OpenSearch Dashboards 不译)、可视化(visualization)、告警(alerting)、监控器(monitor)、角色(role)、权限(permission)、租户(tenant)。 + 查询与聚合:全文查询(full-text query)、词项级查询(term-level query)、复合查询(compound query)、查询上下文 / 过滤上下文(query context / filter context)、权重提升(boost)、命中(hit)、桶(bucket)、管道聚合(Pipeline Aggregation)、同级聚合(Sibling Aggregation)、父聚合(Parent Aggregation)、最少应匹配数(minimum should match)。 + 文本分析与字段:词元(token)、字符过滤器(character filter)、规范化器(normalizer)、字段类型(field type)、地理点(geopoint)、地理形状(geoshape)、扁平对象(flat object)、日期计算(date math)、纪元(epoch)、补全建议器(completion suggester)、载荷(payload)。doc values、shingle 不译。 + 搜索:搜索管道(search pipeline)、搜索请求处理器 / 搜索响应处理器 / 搜索阶段结果处理器、近似 k-NN / 精确 k-NN、向量(vector)、嵌入(embedding)、稠密 / 稀疏向量、语义搜索、关键词搜索、多模态搜索、对话式搜索、神经稀疏搜索、检索增强生成(RAG)、重排序(reranking)、归一化 / 组合方法、模型(model)、连接器(connector)、异步搜索、并发段搜索、高亮(highlighting)、高亮器(highlighter)、分页、时间点(PIT)、滚动(scroll)、自动补全(autocomplete)、建议器(suggester)、拼写纠错(did-you-mean)、预过滤 / 后过滤、切片(slice)、预热(warmup)、游标(cursor)、标识符(identifier)。retrieve 一类 API 操作译为「获取」,不译为「检索」(避免与 retrieval 混淆)。 + 搜索管道处理器页面的 frontmatter `title` 保留英文类型名(与英文侧边栏一致),一级标题写成「Collapse 处理器」。SQL 子句名(Select、Where 等)和 SQL 函数名作标题时保留英文。 + 设置项与表格:Static / Dynamic → 静态 / 动态,Optional / Required → 可选 / 必需,Default → 默认值,Yes / No → 是 / 否。`
` 中的 `Response` 译为「响应」。 + 以查询类型或字段类型命名的页面,标题保留英文类型名,例如「Term 查询」「Keyword 字段类型」。 3. 产品名、库名、API 名称和代码标识符保持英文:OpenSearch、OpenSearch Dashboards、Data Prepper、OpenSearch Benchmark、Lucene、Query DSL、PPL、SQL、k-NN、`_search`、`match`、`bool` 等。API 的端点、参数名和字段名保持英文。 4. **不翻译**:代码块内的代码、行内代码(反引号内)、文件路径、命令、URL、HTML 标签和属性、Vue/VitePress 组件标签及属性名(例如 `` 中的 `text` 值保留英文)。代码块中的**注释**可以翻译。 - 代码块的整行 fence(包括 ```` ```json ```` 这类语言标记)保持原样,不要翻译。 @@ -23,4 +29,5 @@ 6. **链接**:链接地址保持原样(站内的 `/xxx` 链接会自动指向中文页面),只翻译链接文字。锚点链接(`#some-heading`)保持原样。 - 标题锚点不用手动处理:`scripts/sync-zh.mjs` 构建时会按顺序把中文标题与英文标题配对,自动加上英文锚点 `{#english-slug}`。因此**译文的标题数量和顺序必须与原文完全一致**,不能合并、拆分或增删标题。原文已有的 `{#xxx}` 保持原样。 7. 中英文之间、中文与数字之间加一个空格。中文语境下使用全角标点(,。:;?!「」()),代码和英文内容中保持半角。 + - 强调用 `*斜体*` 而不是 `_斜体_`(下划线紧挨中文时不生效);`**粗体**` 以全角括号结尾且后面直接跟中文时,在结尾标记后加一个空格,否则粗体不生效。 8. 不要增删内容,不要添加译者注,除非原文有明显错误。 diff --git a/i18n/zh/aggregations/bucket/adjacency-matrix.md b/i18n/zh/aggregations/bucket/adjacency-matrix.md new file mode 100644 index 00000000..dbc1ff56 --- /dev/null +++ b/i18n/zh/aggregations/bucket/adjacency-matrix.md @@ -0,0 +1,94 @@ +--- +title: 邻接矩阵 +--- + +# 邻接矩阵聚合 + +`adjacency_matrix` 聚合(Aggregation)允许你定义过滤器表达式,并返回一个由相交过滤器构成的矩阵,矩阵中每个非空单元格都代表一个桶(Bucket)。借助它,你可以了解有多少文档(Document)落在任意过滤器组合之中。 + +使用 `adjacency_matrix` 聚合,可以通过将数据可视化为图来发现各个概念之间的关系。 + +例如,要在电子商务示例数据集中分析不同制造商之间的关系: + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "interactions": { + "adjacency_matrix": { + "filters": { + "grpA": { + "match": { + "manufacturer.keyword": "Low Tide Media" + } + }, + "grpB": { + "match": { + "manufacturer.keyword": "Elitelligence" + } + }, + "grpC": { + "match": { + "manufacturer.keyword": "Oceanavigations" + } + } + } + } + } + } +} +``` + +#### 示例响应 + + ```json + { + ... + "aggregations" : { + "interactions" : { + "buckets" : [ + { + "key" : "grpA", + "doc_count" : 1553 + }, + { + "key" : "grpA&grpB", + "doc_count" : 590 + }, + { + "key" : "grpA&grpC", + "doc_count" : 329 + }, + { + "key" : "grpB", + "doc_count" : 1370 + }, + { + "key" : "grpB&grpC", + "doc_count" : 299 + }, + { + "key" : "grpC", + "doc_count" : 1218 + } + ] + } + } + } +``` + + 我们来仔细看看这个结果: + + ```json + { + "key" : "grpA&grpB", + "doc_count" : 590 + } + ``` + +- `grpA`:由 Low Tide Media 制造的产品。 +- `grpB`:由 Elitelligence 制造的产品。 +- `590`:由这两家共同制造的产品数量。 + +你可以使用 OpenSearch Dashboards 以网络图的形式呈现这些数据。 diff --git a/i18n/zh/aggregations/bucket/date-histogram.md b/i18n/zh/aggregations/bucket/date-histogram.md new file mode 100644 index 00000000..f37c761f --- /dev/null +++ b/i18n/zh/aggregations/bucket/date-histogram.md @@ -0,0 +1,54 @@ +--- +title: 日期直方图 +--- + +# 日期直方图聚合 + +`date_histogram` 聚合(Aggregation)使用[日期数学表达式](/field-types/supported-field-types/date#date-math)为时间序列数据生成直方图。 + +例如,你可以统计网站每个月的访问次数: + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "logs_per_month": { + "date_histogram": { + "field": "@timestamp", + "interval": "month" + } + } + } +} +``` + +#### 示例响应 + +```json +... +"aggregations" : { + "logs_per_month" : { + "buckets" : [ + { + "key_as_string" : "2020-10-01T00:00:00.000Z", + "key" : 1601510400000, + "doc_count" : 1635 + }, + { + "key_as_string" : "2020-11-01T00:00:00.000Z", + "key" : 1604188800000, + "doc_count" : 6844 + }, + { + "key_as_string" : "2020-12-01T00:00:00.000Z", + "key" : 1606780800000, + "doc_count" : 5595 + } + ] + } +} +} +``` + +响应中包含三个月的日志。如果将这些值绘制成图表,你就可以看到网站请求流量逐月的高峰和低谷。 diff --git a/i18n/zh/aggregations/bucket/date-range.md b/i18n/zh/aggregations/bucket/date-range.md new file mode 100644 index 00000000..e1304408 --- /dev/null +++ b/i18n/zh/aggregations/bucket/date-range.md @@ -0,0 +1,50 @@ +--- +title: 日期范围 +--- + +# 日期范围聚合 + +`date_range` 聚合(Aggregation)在概念上与 `range` 聚合相同,区别在于它允许你使用日期数学表达式。 +例如,你可以获取最近 10 天的所有文档(Document)。为了让日期更易读,可以通过 `format` 参数指定格式: + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "number_of_bytes": { + "date_range": { + "field": "@timestamp", + "format": "MM-yyyy", + "ranges": [ + { + "from": "now-10d/d", + "to": "now" + } + ] + } + } + } +} +``` + +#### 示例响应 + +```json +... +"aggregations" : { + "number_of_bytes" : { + "buckets" : [ + { + "key" : "03-2021-03-2021", + "from" : 1.6145568E12, + "from_as_string" : "03-2021", + "to" : 1.615451329043E12, + "to_as_string" : "03-2021", + "doc_count" : 0 + } + ] + } + } +} +``` diff --git a/i18n/zh/aggregations/bucket/diversified-sampler.md b/i18n/zh/aggregations/bucket/diversified-sampler.md new file mode 100644 index 00000000..d9755383 --- /dev/null +++ b/i18n/zh/aggregations/bucket/diversified-sampler.md @@ -0,0 +1,58 @@ +--- +title: 多样化采样器 +--- + +# 多样化采样器 + +`diversified_sampler` 聚合(Aggregation)通过对包含相同 `field` 值的文档(Document)进行去重,减少样本池分布中的偏差。它使用 `max_docs_per_value` 和 `field` 设置来实现这一点,这两个设置限制了在一个分片(Shard)上针对所提供的 `field` 收集的最大文档数。`max_docs_per_value` 设置是一个可选参数,用于确定每个 `field` 值最多返回的文档数,其默认值为 `1`。 + +与 [`sampler` 聚合](/aggregations/bucket/sampler)类似,你可以使用 `shard_size` 设置来控制在任意一个分片上收集的最大文档数,如下例所示: + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "sample": { + "diversified_": { + "shard_size": 1000, + "field": "response.keyword" + }, + "aggs": { + "terms": { + "terms": { + "field": "agent.keyword" + } + } + } + } + } +} +``` + +#### 示例响应 + +```json +... +"aggregations" : { + "sample" : { + "doc_count" : 3, + "terms" : { + "doc_count_error_upper_bound" : 0, + "sum_other_doc_count" : 0, + "buckets" : [ + { + "key" : "Mozilla/5.0 (X11; Linux x86_64; rv:6.0a1) Gecko/20110421 Firefox/6.0a1", + "doc_count" : 2 + }, + { + "key" : "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)", + "doc_count" : 1 + } + ] + } + } + + } +} +``` diff --git a/i18n/zh/aggregations/bucket/filter.md b/i18n/zh/aggregations/bucket/filter.md new file mode 100644 index 00000000..7388189f --- /dev/null +++ b/i18n/zh/aggregations/bucket/filter.md @@ -0,0 +1,49 @@ +--- +title: 过滤器 +--- + +# 过滤器聚合 + +`filter` 聚合(Aggregation)是一个查询子句,与搜索查询(Query)完全相同,例如 `match`、`term` 或 `range`。在创建桶(Bucket)之前,你可以使用 `filter` 聚合将整个文档(Document)集合缩小为一个特定的集合。 + +下面的示例展示了在过滤器上下文中运行的 `avg` 聚合。`avg` 聚合只对与 `range` 查询匹配的文档进行聚合: + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "low_value": { + "filter": { + "range": { + "taxful_total_price": { + "lte": 50 + } + } + }, + "aggs": { + "avg_amount": { + "avg": { + "field": "taxful_total_price" + } + } + } + } + } +} +``` + +#### 示例响应 + +```json +... +"aggregations" : { + "low_value" : { + "doc_count" : 1633, + "avg_amount" : { + "value" : 38.363175998928355 + } + } + } +} +``` diff --git a/i18n/zh/aggregations/bucket/filters.md b/i18n/zh/aggregations/bucket/filters.md new file mode 100644 index 00000000..862b804b --- /dev/null +++ b/i18n/zh/aggregations/bucket/filters.md @@ -0,0 +1,74 @@ +--- +title: 多过滤器 +--- + +# 多过滤器聚合 + +`filters` 聚合(Aggregation)与 `filter` 聚合相同,区别在于它允许你使用多个过滤器聚合。 +`filter` 聚合只产生一个桶(Bucket),而 `filters` 聚合会返回多个桶,每个已定义的过滤器对应一个桶。 + +要为不匹配任何过滤器查询的所有文档(Document)创建一个桶,请将 `other_bucket` 属性设置为 `true`: + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "200_os": { + "filters": { + "other_bucket": true, + "filters": [ + { + "term": { + "response.keyword": "200" + } + }, + { + "term": { + "machine.os.keyword": "osx" + } + } + ] + }, + "aggs": { + "avg_amount": { + "avg": { + "field": "bytes" + } + } + } + } + } +} +``` + +#### 示例响应 + +```json +... +"aggregations" : { + "200_os" : { + "buckets" : [ + { + "doc_count" : 12832, + "avg_amount" : { + "value" : 5897.852711970075 + } + }, + { + "doc_count" : 2825, + "avg_amount" : { + "value" : 5620.347256637168 + } + }, + { + "doc_count" : 1017, + "avg_amount" : { + "value" : 3247.0963618485744 + } + } + ] + } + } +} +``` diff --git a/i18n/zh/aggregations/bucket/geo-distance.md b/i18n/zh/aggregations/bucket/geo-distance.md new file mode 100644 index 00000000..951e4c50 --- /dev/null +++ b/i18n/zh/aggregations/bucket/geo-distance.md @@ -0,0 +1,153 @@ +--- +title: 地理距离 +--- + +# 地理距离聚合 + +`geo_distance` 聚合(Aggregation)根据与原点 `geo_point` 字段之间的距离,将文档(Document)分组到一系列同心圆中。 +它与 `range` 聚合相同,区别在于它作用于地理位置。 + +例如,你可以使用 `geo_distance` 聚合查找距离你 1 km 以内的所有披萨店。搜索结果被限制在你指定的 1 km 半径内,但你也可以再添加 2 km 以内的结果。 + +`geo_distance` 聚合只能用于映射(Mapping)为 `geo_point` 的字段。 + +点是单个地理坐标,例如智能手机上显示的你的当前位置。在 OpenSearch 中,点的表示方式如下: + +```json +{ + "location": { + "type": "point", + "coordinates": { + "lat": 83.76, + "lon": -81.2 + } + } +} +``` + +你也可以将纬度和经度指定为数组 `[-81.20, 83.76]` 或字符串 `"83.76, -81.20"` + +下表列出了 `geo_distance` 聚合的相关字段: + +字段 | 描述 | 必需 +:--- | :--- |:--- +`field` | 指定要处理的地理点字段。 | 是 +`origin` | 指定用于计算距离的起始地理点。 | 是 +`ranges` | 指定一个范围列表,根据文档与目标点之间的距离来收集文档。 | 是 +`unit` | 定义 `ranges` 数组中使用的单位。`unit` 默认为 `m`(米),但你可以切换为其他单位,例如 `km`(千米)、`mi`(英里)、`in`(英寸)、`yd`(码)、`cm`(厘米)和 `mm`(毫米)。 | 否 +`distance_type` | 指定 OpenSearch 计算距离的方式。默认值为 `sloppy_arc`(速度较快但精度较低),也可以设置为 `arc`(速度较慢但精度最高)或 `plane`(速度最快但精度最低)。由于误差较大,`plane` 只应用于较小的地理区域。 | 否 + +语法如下: + +```json +{ + "aggs": { + "aggregation_name": { + "geo_distance": { + "field": "field_1", + "origin": "x, y", + "ranges": [ + { + "to": "value_1" + }, + { + "from": "value_2", + "to": "value_3" + }, + { + "from": "value_4" + } + ] + } + } + } +} +``` + +此示例根据与 `geo-point` 字段之间的以下距离来构建桶(Bucket): + +- 小于 10 km +- 10 至 20 km +- 20 至 50 km +- 50 至 100 km +- 大于 100 km + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "position": { + "geo_distance": { + "field": "geo.coordinates", + "origin": { + "lat": 83.76, + "lon": -81.2 + }, + "ranges": [ + { + "to": 10 + }, + { + "from": 10, + "to": 20 + }, + { + "from": 20, + "to": 50 + }, + { + "from": 50, + "to": 100 + }, + { + "from": 100 + } + ] + } + } + } +} +``` + +#### 示例响应 + +```json +... +"aggregations" : { + "position" : { + "buckets" : [ + { + "key" : "*-10.0", + "from" : 0.0, + "to" : 10.0, + "doc_count" : 0 + }, + { + "key" : "10.0-20.0", + "from" : 10.0, + "to" : 20.0, + "doc_count" : 0 + }, + { + "key" : "20.0-50.0", + "from" : 20.0, + "to" : 50.0, + "doc_count" : 0 + }, + { + "key" : "50.0-100.0", + "from" : 50.0, + "to" : 100.0, + "doc_count" : 0 + }, + { + "key" : "100.0-*", + "from" : 100.0, + "doc_count" : 14074 + } + ] + } + } +} +``` diff --git a/i18n/zh/aggregations/bucket/geohash-grid.md b/i18n/zh/aggregations/bucket/geohash-grid.md new file mode 100644 index 00000000..23cf2059 --- /dev/null +++ b/i18n/zh/aggregations/bucket/geohash-grid.md @@ -0,0 +1,268 @@ +--- +title: Geohash 网格 +--- + +# Geohash 网格聚合 + +`geohash_grid` 聚合(Aggregation)将文档(Document)分入桶(Bucket)中以进行地理分析。它将一个地理区域划分为由不同大小或精度的较小区域组成的网格。精度值越低,代表的地理区域越大;精度值越高,代表的地理区域越小、越精确。你可以使用 geohash 网格聚合对 [geopoint](/field-types/supported-field-types/geo-point) 或 [geoshape](/field-types/supported-field-types/geo-shape) 字段中的文档进行聚合。一个显著的区别是:geopoint 只会出现在一个桶中,而 geoshape 会计入与之相交的所有 geohash 网格单元。 + +查询(Query)返回的结果可能多到无法在地图上逐个显示每个 geopoint。`geohash_grid` 聚合按照你定义的精度级别(介于 1 到 12 之间,默认为 5)计算每个点的 geohash,从而将邻近的 geopoint 归入同一个桶中。要了解有关 geohash 的更多信息,请参阅 [Wikipedia](https://en.wikipedia.org/wiki/Geohash)。 + +Web 日志示例数据分布在较大的地理区域中,因此可以使用较低的精度值。你可以通过提高精度值来放大此地图: + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "geo_hash": { + "geohash_grid": { + "field": "geo.coordinates", + "precision": 4 + } + } + } +} +``` + +#### 示例响应 + +```json +... +"aggregations" : { + "geo_hash" : { + "buckets" : [ + { + "key" : "c1cg", + "doc_count" : 104 + }, + { + "key" : "dr5r", + "doc_count" : 26 + }, + { + "key" : "9q5b", + "doc_count" : 20 + }, + { + "key" : "c20g", + "doc_count" : 19 + }, + { + "key" : "dr70", + "doc_count" : 18 + } + ... + ] + } + } +} +``` + +你可以使用 OpenSearch Dashboards 在地图上可视化聚合响应。 + +你希望聚合越精确,OpenSearch 消耗的资源就越多,因为聚合需要计算的桶数量会随之增加。默认情况下,OpenSearch 生成的桶不会超过 10,000 个。你可以使用 `size` 属性更改此行为,但请记住,对于包含数千个桶的超大范围查询,性能可能会受到影响。 + +## 聚合 geoshape + +要对 geoshape 字段执行聚合,首先创建一个索引(Index),并将 `location` 字段映射为 `geo_shape`: + +```json +PUT national_parks +{ + "mappings": { + "properties": { + "location": { + "type": "geo_shape" + } + } + } +} +``` + +接下来,向 `national_parks` 索引中索引一些文档: + +```json +PUT national_parks/_doc/1 +{ + "name": "Yellowstone National Park", + "location": + {"type": "envelope","coordinates": [ [-111.15, 45.12], [-109.83, 44.12] ]} +} +``` + +```json +PUT national_parks/_doc/2 +{ + "name": "Yosemite National Park", + "location": + {"type": "envelope","coordinates": [ [-120.23, 38.16], [-119.05, 37.45] ]} +} +``` + +```json +PUT national_parks/_doc/3 +{ + "name": "Death Valley National Park", + "location": + {"type": "envelope","coordinates": [ [-117.34, 37.01], [-116.38, 36.25] ]} +} +``` + +你可以按如下方式对 `location` 字段执行聚合: + +```json +GET national_parks/_search +{ + "aggregations": { + "grouped": { + "geohash_grid": { + "field": "location", + "precision": 1 + } + } + } +} +``` + +聚合 geoshape 时,一个 geoshape 可能会被计入多个桶,因为它与多个网格单元重叠: + +
+ + 响应 + + +```json +{ + "took" : 24, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 3, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "national_parks", + "_id" : "1", + "_score" : 1.0, + "_source" : { + "name" : "Yellowstone National Park", + "location" : { + "type" : "envelope", + "coordinates" : [ + [ + -111.15, + 45.12 + ], + [ + -109.83, + 44.12 + ] + ] + } + } + }, + { + "_index" : "national_parks", + "_id" : "2", + "_score" : 1.0, + "_source" : { + "name" : "Yosemite National Park", + "location" : { + "type" : "envelope", + "coordinates" : [ + [ + -120.23, + 38.16 + ], + [ + -119.05, + 37.45 + ] + ] + } + } + }, + { + "_index" : "national_parks", + "_id" : "3", + "_score" : 1.0, + "_source" : { + "name" : "Death Valley National Park", + "location" : { + "type" : "envelope", + "coordinates" : [ + [ + -117.34, + 37.01 + ], + [ + -116.38, + 36.25 + ] + ] + } + } + } + ] + }, + "aggregations" : { + "grouped" : { + "buckets" : [ + { + "key" : "9", + "doc_count" : 3 + }, + { + "key" : "c", + "doc_count" : 1 + } + ] + } + } +} +``` +
+ +::: info 注意 +目前,OpenSearch 支持通过 API 执行 geoshape 聚合,但 OpenSearch Dashboards 可视化尚不支持。如果你希望在可视化中实现 geoshape 聚合,请为相关的 [GitHub issue](https://github.com/opensearch-project/dashboards-maps/issues/250) 投票。 +::: + +## 支持的参数 + +Geohash 网格聚合请求支持以下参数。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +field | String | 执行聚合的字段。该字段必须映射为 `geo_point` 或 `geo_shape` 字段。如果该字段包含数组,则会聚合所有数组值。必需。 +precision | Integer | 用于确定网格单元以对结果进行分桶的粒度级别。单元不能超过所需精度的指定大小(对角线)。有效值范围为 [0, 12]。可选。默认值为 5。 +bounds | Object | 用于过滤 geopoint 和 geoshape 的边界框。边界框由左上角和右下角顶点定义。只有与该边界框相交或完全被该边界框包围的形状才会包含在聚合输出中。顶点以 geopoint 的形式指定,可使用以下任一格式:
- 包含纬度和经度的对象
- [`longitude`, `latitude`] 格式的数组
- "`latitude`,`longitude`" 格式的字符串
- geohash
- WKT
有关格式示例,请参阅 [geopoint 格式](/field-types/supported-field-types/geo-point#formats)。可选。 +size | Integer | 要返回的最大桶数。当桶的数量多于 `size` 时,OpenSearch 返回包含文档较多的桶。可选。默认值为 10,000。 +shard_size | Integer | 每个分片(Shard)返回的最大桶数。可选。默认值为 max (10, `size` · 分片数),这样可以为优先级更高的桶提供更准确的计数。 + +## Geohash 精度 + +下表描述了 geohash 精度与网格单元近似尺寸之间的关系。 + +精度 /
geohash 长度 | 纬度位数 | 经度位数 | 纬度误差 | 经度误差 | 单元高度 | 单元宽度 +:---:|:-------------:|:--------------:|:--------------:|:---------------:|:-----------:|:----------: + 1 | 2 | 3 | ±23 | ±23 | 4992.6 km | 5009.4 km + 2 | 5 | 5 | ±2.8 | ±5.6 | 624.1 km | 1252.3 km + 3 | 7 | 8 | ±0.70 | ±0.70 | 156 km | 156.5 km + 4 | 10 | 10 | ±0.087 | ±0.18 | 19.5 km | 39.1 km + 5 | 12 | 13 | ±0.022 | ±0.022 | 4.9 km | 4.9 km + 6 | 15 | 15 | ±0.0027 | ±0.0055 | 609.4 m | 1.2 km + 7 | 17 | 18 | ±0.00068 | ±0.00068 | 152.5 m | 152.9 m + 8 | 20 | 20 | ±0.00086 | ±0.000172 | 19 m | 38.2 m + 9 | 22 | 23 | ±0.000021 | ±0.000021 | 4.8 m | 4.8 m + 10 | 25 | 25 | ±0.00000268 | ±0.00000536 | 59.5 cm | 1.2 m + 11 | 27 | 28 | ±0.00000067 | ±0.00000067 | 14.9 cm | 14.9 cm + 12 | 30 | 30 | ±0.00000008 | ±0.00000017 | 1.9 cm | 3.7 cm diff --git a/i18n/zh/aggregations/bucket/geohex-grid.md b/i18n/zh/aggregations/bucket/geohex-grid.md new file mode 100644 index 00000000..24742ccc --- /dev/null +++ b/i18n/zh/aggregations/bucket/geohex-grid.md @@ -0,0 +1,379 @@ +--- +title: Geohex 网格 +--- + +# Geohex 网格聚合 + +六边形分层地理空间索引系统(Hexagonal Hierarchical Geospatial Indexing System,H3)将地球表面划分为可识别的六边形单元。 + +H3 网格系统克服了 Geohash 分区不均匀的局限,因此非常适合邻近性应用。Geohash 对经纬度对进行编码,导致两极附近的分区明显更小,而赤道附近的分区则相当于一个经度。相比之下,H3 网格系统的形变很小,并且仅限于 122 个分区中的 5 个。这五个分区被放置在很少使用的区域(例如大洋中央),从而使重要区域没有误差。因此,基于 H3 网格系统对文档(Document)进行分组,可以获得比 Geohash 网格更好的聚合(Aggregation)效果。 + +geohex 网格聚合将 [geopoint](/field-types/supported-field-types/geo-point) 分组到网格单元中以进行地理分析。每个网格单元对应一个 [H3 单元](https://h3geo.org/docs/core-library/h3Indexing/#h3-cell-indexp),并使用 [H3Index 表示法](https://h3geo.org/docs/core-library/h3Indexing/#h3index-representation)进行标识。 + +## 精度 + +`precision` 参数控制决定网格单元大小的粒度级别。精度越低,网格单元越大。 + +以下示例演示了低精度和高精度的聚合请求。 + +首先,创建一个索引(Index),并将 `location` 字段映射为 `geo_point`: + +```json +PUT national_parks +{ + "mappings": { + "properties": { + "location": { + "type": "geo_point" + } + } + } +} +``` + +将以下文档(Document)索引到示例索引中: + +```json +PUT national_parks/_doc/1 +{ + "name": "Yellowstone National Park", + "location": "44.42, -110.59" +} +``` + +```json +PUT national_parks/_doc/2 +{ + "name": "Yosemite National Park", + "location": "37.87, -119.53" +} +``` + +```json +PUT national_parks/_doc/3 +{ + "name": "Death Valley National Park", + "location": "36.53, -116.93" +} +``` + +::: info 注意 +你可以使用多种格式来索引 geopoint。有关所有支持格式的列表,请参阅 [geopoint 文档](/field-types/supported-field-types/geo-point#formats)。 +::: + +## 低精度请求 + +运行一个低精度请求,将全部三个文档归入同一个桶(Bucket): + +```json +GET national_parks/_search +{ + "aggregations": { + "grouped": { + "geohex_grid": { + "field": "location", + "precision": 1 + } + } + } +} +``` + +::: info 注意 +geohex 网格聚合查询既可以使用 `GET` HTTP 方法,也可以使用 `POST` HTTP 方法。 +::: + +响应将文档 2 和文档 3 分在了一组,因为它们距离足够近,可以归入同一个网格单元: + +```json +{ + "took" : 4, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 3, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "national_parks", + "_id" : "1", + "_score" : 1.0, + "_source" : { + "name" : "Yellowstone National Park", + "location" : "44.42, -110.59" + } + }, + { + "_index" : "national_parks", + "_id" : "2", + "_score" : 1.0, + "_source" : { + "name" : "Yosemite National Park", + "location" : "37.87, -119.53" + } + }, + { + "_index" : "national_parks", + "_id" : "3", + "_score" : 1.0, + "_source" : { + "name" : "Death Valley National Park", + "location" : "36.53, -116.93" + } + } + ] + }, + "aggregations" : { + "grouped" : { + "buckets" : [ + { + "key" : "8129bffffffffff", + "doc_count" : 2 + }, + { + "key" : "8128bffffffffff", + "doc_count" : 1 + } + ] + } + } +} +``` + +## 高精度请求 + +现在运行一个高精度请求: + +```json +GET national_parks/_search +{ + "aggregations": { + "grouped": { + "geohex_grid": { + "field": "location", + "precision": 6 + } + } + } +} +``` + +由于粒度更高,三个文档被分别归入不同的桶: + +```json +{ + "took" : 5, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 3, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "national_parks", + "_id" : "1", + "_score" : 1.0, + "_source" : { + "name" : "Yellowstone National Park", + "location" : "44.42, -110.59" + } + }, + { + "_index" : "national_parks", + "_id" : "2", + "_score" : 1.0, + "_source" : { + "name" : "Yosemite National Park", + "location" : "37.87, -119.53" + } + }, + { + "_index" : "national_parks", + "_id" : "3", + "_score" : 1.0, + "_source" : { + "name" : "Death Valley National Park", + "location" : "36.53, -116.93" + } + } + ] + }, + "aggregations" : { + "grouped" : { + "buckets" : [ + { + "key" : "8629ab6dfffffff", + "doc_count" : 1 + }, + { + "key" : "8629857a7ffffff", + "doc_count" : 1 + }, + { + "key" : "862896017ffffff", + "doc_count" : 1 + } + ] + } + } +} +``` + +## 过滤请求 + +高精度请求会消耗大量资源,因此我们建议使用 `geo_bounding_box` 之类的过滤器来限制地理区域。例如,以下查询应用了一个过滤器来限制搜索区域: + +```json +GET national_parks/_search +{ + "size" : 0, + "aggregations": { + "filtered": { + "filter": { + "geo_bounding_box": { + "location": { + "top_left": "38, -120", + "bottom_right": "36, -116" + } + } + }, + "aggregations": { + "grouped": { + "geohex_grid": { + "field": "location", + "precision": 6 + } + } + } + } + } +} +``` + +响应中包含位于 `geo_bounding_box` 边界内的两个文档: + +```json +{ + "took" : 4, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 3, + "relation" : "eq" + }, + "max_score" : null, + "hits" : [ ] + }, + "aggregations" : { + "filtered" : { + "doc_count" : 2, + "grouped" : { + "buckets" : [ + { + "key" : "8629ab6dfffffff", + "doc_count" : 1 + }, + { + "key" : "8629857a7ffffff", + "doc_count" : 1 + } + ] + } + } + } +} +``` + +你还可以在 `bounds` 参数中提供边界范围的坐标来限制地理区域。`bounds` 和 `geo_bounding_box` 的坐标都可以使用任意一种 [geopoint 格式](/field-types/supported-field-types/geo-point#formats)来指定。以下查询(Query)对 `bounds` 参数使用了 Well-Known Text(WKT)"POINT(`longitude` `latitude`)" 格式: + +```json +GET national_parks/_search +{ + "size": 0, + "aggregations": { + "grouped": { + "geohex_grid": { + "field": "location", + "precision": 6, + "bounds": { + "top_left": "POINT (-120 38)", + "bottom_right": "POINT (-116 36)" + } + } + } + } +} +``` + +响应中只包含位于指定边界内的两个结果: + +```json +{ + "took" : 3, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 3, + "relation" : "eq" + }, + "max_score" : null, + "hits" : [ ] + }, + "aggregations" : { + "grouped" : { + "buckets" : [ + { + "key" : "8629ab6dfffffff", + "doc_count" : 1 + }, + { + "key" : "8629857a7ffffff", + "doc_count" : 1 + } + ] + } + } +} +``` + +`bounds` 参数既可以与 `geo_bounding_box` 过滤器一起使用,也可以单独使用;这两个参数相互独立,彼此之间可以存在任意空间关系。 + +## 支持的参数 + +Geohex 网格聚合请求支持以下参数。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +field | String | 包含 geopoint 的字段。该字段必须映射为 `geo_point` 字段。如果该字段包含数组,则会聚合所有数组值。必需。 +precision | Integer | 用于确定网格单元以对结果进行分桶的粒度级别。单元不能超过所需精度的指定大小(对角线)。有效值范围为 [0, 15]。可选。默认值为 5。 +bounds | Object | 用于过滤 geopoint 的边界框。边界框由左上角和右下角顶点定义。顶点以 geopoint 的形式指定,可使用以下任一格式:
- 包含纬度和经度的对象
- [`longitude`, `latitude`] 格式的数组
- "`latitude`,`longitude`" 格式的字符串
- geohash
- WKT
有关格式示例,请参阅 [geopoint 格式](/field-types/supported-field-types/geo-point#formats)。可选。 +size | Integer | 要返回的最大桶数。当桶的数量多于 `size` 时,OpenSearch 返回包含文档较多的桶。可选。默认值为 10,000。 +shard_size | Integer | 每个分片(Shard)返回的最大桶数。可选。默认值为 max (10, `size` · 分片数),这样可以为优先级更高的桶提供更准确的计数。 diff --git a/i18n/zh/aggregations/bucket/geotile-grid.md b/i18n/zh/aggregations/bucket/geotile-grid.md new file mode 100644 index 00000000..1a52779a --- /dev/null +++ b/i18n/zh/aggregations/bucket/geotile-grid.md @@ -0,0 +1,531 @@ +--- +title: Geotile 网格 +--- + +# Geotile 网格聚合 + +geotile 网格聚合(Aggregation)将文档(Document)分组到网格单元中以进行地理分析。每个网格单元对应一个[地图瓦片](https://en.wikipedia.org/wiki/Tiled_web_map),并使用 `{zoom}/{x}/{y}` 格式进行标识。你可以使用 geotile 网格聚合对 [geopoint](/field-types/supported-field-types/geo-point) 或 [geoshape](/field-types/supported-field-types/geo-shape) 字段中的文档进行聚合。一个显著的区别是:geopoint 只会出现在一个桶(Bucket)中,而 geoshape 会计入与之相交的所有 geotile 网格单元。 + +## 精度 + +`precision` 参数控制决定网格单元大小的粒度级别。精度越低,网格单元越大。 + +以下示例演示了低精度和高精度的聚合请求。 + +首先,创建一个索引(Index),并将 `location` 字段映射为 `geo_point`: + +```json +PUT national_parks +{ + "mappings": { + "properties": { + "location": { + "type": "geo_point" + } + } + } +} +``` + +将以下文档(Document)索引到示例索引中: + +```json +PUT national_parks/_doc/1 +{ + "name": "Yellowstone National Park", + "location": "44.42, -110.59" +} +``` + +```json +PUT national_parks/_doc/2 +{ + "name": "Yosemite National Park", + "location": "37.87, -119.53" +} +``` + +```json +PUT national_parks/_doc/3 +{ + "name": "Death Valley National Park", + "location": "36.53, -116.93" +} +``` + +::: info 注意 +你可以使用多种格式来索引 geopoint。有关所有支持格式的列表,请参阅 [geopoint 文档](/field-types/supported-field-types/geo-point#formats)。 +::: + +## 低精度请求 + +运行一个低精度请求,将全部三个文档归入同一个桶(Bucket): + +```json +GET national_parks/_search +{ + "aggregations": { + "grouped": { + "geotile_grid": { + "field": "location", + "precision": 1 + } + } + } +} +``` + +::: info 注意 +geotile 网格聚合查询既可以使用 `GET` HTTP 方法,也可以使用 `POST` HTTP 方法。 +::: + +响应将所有文档分在了一组,因为它们距离足够近,可以归入同一个网格单元: + +
+ + 响应 + + +```json +{ + "took": 51, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 3, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "national_parks", + "_id": "1", + "_score": 1, + "_source": { + "name": "Yellowstone National Park", + "location": "44.42, -110.59" + } + }, + { + "_index": "national_parks", + "_id": "2", + "_score": 1, + "_source": { + "name": "Yosemite National Park", + "location": "37.87, -119.53" + } + }, + { + "_index": "national_parks", + "_id": "3", + "_score": 1, + "_source": { + "name": "Death Valley National Park", + "location": "36.53, -116.93" + } + } + ] + }, + "aggregations": { + "grouped": { + "buckets": [ + { + "key": "1/0/0", + "doc_count": 3 + } + ] + } + } +} +``` +
+ +## 高精度请求 + +现在运行一个高精度请求: + +```json +GET national_parks/_search +{ + "aggregations": { + "grouped": { + "geotile_grid": { + "field": "location", + "precision": 6 + } + } + } +} +``` + +由于粒度更高,三个文档被分别归入不同的桶: + +
+ + 响应 + + +```json +{ + "took": 15, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 3, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "national_parks", + "_id": "1", + "_score": 1, + "_source": { + "name": "Yellowstone National Park", + "location": "44.42, -110.59" + } + }, + { + "_index": "national_parks", + "_id": "2", + "_score": 1, + "_source": { + "name": "Yosemite National Park", + "location": "37.87, -119.53" + } + }, + { + "_index": "national_parks", + "_id": "3", + "_score": 1, + "_source": { + "name": "Death Valley National Park", + "location": "36.53, -116.93" + } + } + ] + }, + "aggregations": { + "grouped": { + "buckets": [ + { + "key": "6/12/23", + "doc_count": 1 + }, + { + "key": "6/11/25", + "doc_count": 1 + }, + { + "key": "6/10/24", + "doc_count": 1 + } + ] + } + } +} +``` +
+ +你还可以在 `bounds` 参数中提供边界范围的坐标来限制地理区域。`bounds` 和 `geo_bounding_box` 的坐标都可以使用任意一种 [geopoint 格式](/field-types/supported-field-types/geo-point#formats)来指定。以下查询(Query)对 `bounds` 参数使用了 Well-Known Text(WKT)"POINT(`longitude` `latitude`)" 格式: + +```json +GET national_parks/_search +{ + "size": 0, + "aggregations": { + "grouped": { + "geotile_grid": { + "field": "location", + "precision": 6, + "bounds": { + "top_left": "POINT (-120 38)", + "bottom_right": "POINT (-116 36)" + } + } + } + } +} +``` + +响应中只包含位于指定边界内的两个结果: + +
+ + 响应 + + +```json +{ + "took": 48, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 3, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "national_parks", + "_id": "1", + "_score": 1, + "_source": { + "name": "Yellowstone National Park", + "location": "44.42, -110.59" + } + }, + { + "_index": "national_parks", + "_id": "2", + "_score": 1, + "_source": { + "name": "Yosemite National Park", + "location": "37.87, -119.53" + } + }, + { + "_index": "national_parks", + "_id": "3", + "_score": 1, + "_source": { + "name": "Death Valley National Park", + "location": "36.53, -116.93" + } + } + ] + }, + "aggregations": { + "grouped": { + "buckets": [ + { + "key": "6/11/25", + "doc_count": 1 + }, + { + "key": "6/10/24", + "doc_count": 1 + } + ] + } + } +} +``` +
+ +`bounds` 参数既可以与 `geo_bounding_box` 过滤器一起使用,也可以单独使用;这两个参数相互独立,彼此之间可以存在任意空间关系。 + +## 聚合 geoshape + +要对 geoshape 字段执行聚合,首先创建一个索引,并将 `location` 字段映射为 `geo_shape`: + +```json +PUT national_parks +{ + "mappings": { + "properties": { + "location": { + "type": "geo_shape" + } + } + } +} +``` + +接下来,向 `national_parks` 索引中索引一些文档: + +```json +PUT national_parks/_doc/1 +{ + "name": "Yellowstone National Park", + "location": + {"type": "envelope","coordinates": [ [-111.15, 45.12], [-109.83, 44.12] ]} +} +``` + +```json +PUT national_parks/_doc/2 +{ + "name": "Yosemite National Park", + "location": + {"type": "envelope","coordinates": [ [-120.23, 38.16], [-119.05, 37.45] ]} +} +``` + +```json +PUT national_parks/_doc/3 +{ + "name": "Death Valley National Park", + "location": + {"type": "envelope","coordinates": [ [-117.34, 37.01], [-116.38, 36.25] ]} +} +``` + +你可以按如下方式对 `location` 字段执行聚合: + +```json +GET national_parks/_search +{ + "aggregations": { + "grouped": { + "geotile_grid": { + "field": "location", + "precision": 6 + } + } + } +} +``` + +聚合 geoshape 时,一个 geoshape 可能会被计入多个桶,因为它与多个网格单元重叠: + +
+ + 响应 + + +```json +{ + "took" : 3, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 3, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "national_parks", + "_id" : "1", + "_score" : 1.0, + "_source" : { + "name" : "Yellowstone National Park", + "location" : { + "type" : "envelope", + "coordinates" : [ + [ + -111.15, + 45.12 + ], + [ + -109.83, + 44.12 + ] + ] + } + } + }, + { + "_index" : "national_parks", + "_id" : "2", + "_score" : 1.0, + "_source" : { + "name" : "Yosemite National Park", + "location" : { + "type" : "envelope", + "coordinates" : [ + [ + -120.23, + 38.16 + ], + [ + -119.05, + 37.45 + ] + ] + } + } + }, + { + "_index" : "national_parks", + "_id" : "3", + "_score" : 1.0, + "_source" : { + "name" : "Death Valley National Park", + "location" : { + "type" : "envelope", + "coordinates" : [ + [ + -117.34, + 37.01 + ], + [ + -116.38, + 36.25 + ] + ] + } + } + } + ] + }, + "aggregations" : { + "grouped" : { + "buckets" : [ + { + "key" : "6/12/23", + "doc_count" : 1 + }, + { + "key" : "6/12/22", + "doc_count" : 1 + }, + { + "key" : "6/11/25", + "doc_count" : 1 + }, + { + "key" : "6/11/24", + "doc_count" : 1 + }, + { + "key" : "6/10/24", + "doc_count" : 1 + } + ] + } + } +} +``` +
+ +::: info 注意 +目前,OpenSearch 支持通过 API 执行 geoshape 聚合,但 OpenSearch Dashboards 可视化尚不支持。如果你希望在可视化中实现 geoshape 聚合,请为相关的 [GitHub issue](https://github.com/opensearch-project/dashboards-maps/issues/250) 投票。 +::: + +## 支持的参数 + +Geotile 网格聚合请求支持以下参数。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +field | String | 包含 geopoint 的字段。该字段必须映射为 `geo_point` 字段。如果该字段包含数组,则会聚合所有数组值。必需。 +precision | Integer | 用于确定网格单元以对结果进行分桶的粒度级别。单元不能超过所需精度的指定大小(对角线)。有效值范围为 [0, 29]。可选。默认值为 7。 +bounds | Object | 用于过滤 geopoint 的边界框。边界框由左上角和右下角顶点定义。顶点以 geopoint 的形式指定,可使用以下任一格式:
- 包含纬度和经度的对象
- [`longitude`, `latitude`] 格式的数组
- "`latitude`,`longitude`" 格式的字符串
- geohash
- WKT
有关格式示例,请参阅 [geopoint 格式](/field-types/supported-field-types/geo-point#formats)。可选。 +size | Integer | 要返回的最大桶数。当桶的数量多于 `size` 时,OpenSearch 返回包含文档较多的桶。可选。默认值为 10,000。 +shard_size | Integer | 每个分片(Shard)返回的最大桶数。可选。默认值为 max (10, `size` · 分片数),这样可以为优先级更高的桶提供更准确的计数。 diff --git a/i18n/zh/aggregations/bucket/global.md b/i18n/zh/aggregations/bucket/global.md new file mode 100644 index 00000000..4add542a --- /dev/null +++ b/i18n/zh/aggregations/bucket/global.md @@ -0,0 +1,52 @@ +--- +title: 全局 +--- + +# 全局聚合 + +`global` 聚合(Aggregation)可以让你跳出过滤器聚合的聚合上下文。即使你添加了用于缩小文档(Document)集合范围的过滤查询,`global` 聚合也会像该过滤查询不存在一样,对所有文档进行聚合。它会忽略 `filter` 聚合,并隐式采用 `match_all` 查询。 + +以下示例返回索引(Index)中所有文档的 `taxful_total_price` 字段的 `avg` 值: + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "query": { + "range": { + "taxful_total_price": { + "lte": 50 + } + } + }, + "aggs": { + "total_avg_amount": { + "global": {}, + "aggs": { + "avg_price": { + "avg": { + "field": "taxful_total_price" + } + } + } + } + } +} +``` + +#### 示例响应 + +```json +... +"aggregations" : { + "total_avg_amount" : { + "doc_count" : 4675, + "avg_price" : { + "value" : 75.05542864304813 + } + } + } +} +``` + +可以看到,`taxful_total_price` 字段的平均值为 75.05,而不是 `filter` 示例中查询匹配时得到的 38.36。 diff --git a/i18n/zh/aggregations/bucket/histogram.md b/i18n/zh/aggregations/bucket/histogram.md new file mode 100644 index 00000000..091ae88a --- /dev/null +++ b/i18n/zh/aggregations/bucket/histogram.md @@ -0,0 +1,47 @@ +--- +title: 直方图 +--- + +# 直方图聚合 + +`histogram` 聚合(Aggregation)根据指定的间隔将文档(Document)分入桶(Bucket)中。 + +借助 `histogram` 聚合,你可以非常轻松地可视化给定文档范围内值的分布情况。当然,OpenSearch 并不会直接返回一张图表,那是 OpenSearch Dashboards 的工作。但它会返回 JSON 响应,你可以利用该响应自行构建图表。 + +以下示例按 10,000 的间隔对 `number_of_bytes` 字段进行分桶: + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "number_of_bytes": { + "histogram": { + "field": "bytes", + "interval": 10000 + } + } + } +} +``` + +#### 示例响应 + +```json +... +"aggregations" : { + "number_of_bytes" : { + "buckets" : [ + { + "key" : 0.0, + "doc_count" : 13372 + }, + { + "key" : 10000.0, + "doc_count" : 702 + } + ] + } + } +} +``` diff --git a/i18n/zh/aggregations/bucket/index.md b/i18n/zh/aggregations/bucket/index.md new file mode 100644 index 00000000..1b1ad0d1 --- /dev/null +++ b/i18n/zh/aggregations/bucket/index.md @@ -0,0 +1,36 @@ +--- +title: 桶聚合 +--- + +# 桶聚合 + +桶聚合(Bucket Aggregation)将文档(Document)集合归类为桶(Bucket)。桶聚合的类型决定了给定文档所属的桶。 + +你可以使用桶聚合来实现分面导航(通常以侧边栏的形式放在搜索结果页面上),帮助用户筛选结果。 + +## 支持的桶聚合 + +OpenSearch 支持以下桶聚合: + +- [邻接矩阵(Adjacency matrix)](/aggregations/bucket/adjacency-matrix) +- [日期直方图(Date histogram)](/aggregations/bucket/date-histogram) +- [日期范围(Date range)](/aggregations/bucket/date-range) +- [多样化采样器(Diversified sampler)](/aggregations/bucket/diversified-sampler) +- [过滤器(Filter)](/aggregations/bucket/filter) +- [多过滤器(Filters)](/aggregations/bucket/filters) +- [地理距离(Geodistance)](/aggregations/bucket/geo-distance) +- [Geohash 网格(Geohash grid)](/aggregations/bucket/geohash-grid) +- [Geohex 网格(Geohex grid)](/aggregations/bucket/geohex-grid) +- [Geotile 网格(Geotile grid)](/aggregations/bucket/geotile-grid) +- [全局(Global)](/aggregations/bucket/global) +- [直方图(Histogram)](/aggregations/bucket/histogram) +- [IP 范围(IP range)](/aggregations/bucket/ip-range) +- [缺失(Missing)](/aggregations/bucket/missing) +- [多词项(Multi-terms)](/aggregations/bucket/multi-terms) +- [嵌套(Nested)](/aggregations/bucket/nested) +- [范围(Range)](/aggregations/bucket/range) +- [反向嵌套(Reverse nested)](/aggregations/bucket/reverse-nested) +- [采样器(Sampler)](/aggregations/bucket/sampler) +- [显著词项(Significant terms)](/aggregations/bucket/significant-terms) +- [显著文本(Significant text)](/aggregations/bucket/significant-text) +- [词项(Terms)](/aggregations/bucket/terms) diff --git a/i18n/zh/aggregations/bucket/ip-range.md b/i18n/zh/aggregations/bucket/ip-range.md new file mode 100644 index 00000000..78afe3ef --- /dev/null +++ b/i18n/zh/aggregations/bucket/ip-range.md @@ -0,0 +1,70 @@ +--- +title: IP 范围 +--- + +# IP 范围聚合 + +`ip_range` 聚合(Aggregation)用于 IP 地址。 +它适用于 `ip` 类型的字段。你可以使用 [CIDR](https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing) 表示法来定义 IP 范围和掩码。 + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "access": { + "ip_range": { + "field": "ip", + "ranges": [ + { + "from": "1.0.0.0", + "to": "126.158.155.183" + }, + { + "mask": "1.0.0.0/8" + } + ] + } + } + } +} +``` + +#### 示例响应 + +```json +... +"aggregations" : { + "access" : { + "buckets" : [ + { + "key" : "1.0.0.0/8", + "from" : "1.0.0.0", + "to" : "2.0.0.0", + "doc_count" : 98 + }, + { + "key" : "1.0.0.0-126.158.155.183", + "from" : "1.0.0.0", + "to" : "126.158.155.183", + "doc_count" : 7184 + } + ] + } + } +} +``` + +如果你向一个在映射(Mapping)中将 `ip_range` 设置为 `false` 的索引(Index)添加包含格式错误字段的文档(Document),OpenSearch 会拒绝整个文档。你可以将 `ignore_malformed` 设置为 `true`,指定 OpenSearch 忽略格式错误的字段。默认值为 `false`。 + +```json +... +"mappings": { + "properties": { + "ips": { + "type": "ip_range", + "ignore_malformed": true + } + } +} +``` diff --git a/i18n/zh/aggregations/bucket/missing.md b/i18n/zh/aggregations/bucket/missing.md new file mode 100644 index 00000000..db658e7d --- /dev/null +++ b/i18n/zh/aggregations/bucket/missing.md @@ -0,0 +1,75 @@ +--- +title: 缺失 +--- + +# 缺失聚合 + +如果索引(Index)中的某些文档(Document)完全不包含要聚合的字段,或者该字段的值为 NULL,可以使用 `missing` 参数指定这些文档应放入的桶(Bucket)的名称。 + +以下示例将所有缺失值放入名为 "N/A" 的桶中: + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "response_codes": { + "terms": { + "field": "response.keyword", + "size": 10, + "missing": "N/A" + } + } + } +} +``` + +由于 `min_doc_count` 参数的默认值为 1,`missing` 参数不会在响应中返回任何桶。将 `min_doc_count` 参数设置为 0,即可在响应中看到 "N/A" 桶: + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "response_codes": { + "terms": { + "field": "response.keyword", + "size": 10, + "missing": "N/A", + "min_doc_count": 0 + } + } + } +} +``` + +#### 示例响应 + +```json +... +"aggregations" : { + "response_codes" : { + "doc_count_error_upper_bound" : 0, + "sum_other_doc_count" : 0, + "buckets" : [ + { + "key" : "200", + "doc_count" : 12832 + }, + { + "key" : "404", + "doc_count" : 801 + }, + { + "key" : "503", + "doc_count" : 441 + }, + { + "key" : "N/A", + "doc_count" : 0 + } + ] + } + } +} +``` diff --git a/i18n/zh/aggregations/bucket/multi-terms.md b/i18n/zh/aggregations/bucket/multi-terms.md new file mode 100644 index 00000000..500bd87d --- /dev/null +++ b/i18n/zh/aggregations/bucket/multi-terms.md @@ -0,0 +1,119 @@ +--- +title: 多词项 +--- + +# 多词项聚合 + +与 `terms` 桶聚合(Bucket Aggregation)类似,你也可以使用 `multi_terms` 聚合来搜索多个词项。当你需要按文档(Document)数量排序,或者需要按复合键上的指标聚合(Metric Aggregation)排序并获取前 `n` 个结果时,多词项聚合非常有用。例如,你可以搜索特定数量的文档(例如 1000 个),以及每个位置上 CPU 使用率超过 90% 的服务器数量。这个多词项查询(Query)会返回排在前面的若干结果。 + +::: tip 提示 +`multi_terms` 聚合确实比 `terms` 聚合消耗更多内存,因此其性能可能较慢。 +::: + +## 多词项聚合参数 + +参数 | 描述 +:--- | :--- +multi_terms | 表示一个多词项聚合,它根据由多个词项指定的条件将文档归入桶(Bucket)中。 +size | 指定要返回的桶数。默认值为 10。 +order | 表示桶的排序方式。默认情况下,桶按每个桶中的文档数排序。如果多个桶包含相同的文档数,则可以将 `order` 显式设置为按词项值而非文档数排序(例如,将 `order` 设置为 "max-cpu")。 +doc_count | 指定每个桶中要返回的文档数。默认情况下,返回前 10 个词项。 + +#### 示例请求 + +```json +GET sample-index100/_search +{ + "size": 0, + "aggs": { + "hot": { + "multi_terms": { + "terms": [{ + "field": "region" + },{ + "field": "host" + }], + "order": {"max-cpu": "desc"} + }, + "aggs": { + "max-cpu": { "max": { "field": "cpu" } } + } + } + } +} +``` + +#### 示例响应 + +```json +{ + "took": 118, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 8, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "multi-terms": { + "doc_count_error_upper_bound": 0, + "sum_other_doc_count": 0, + "buckets": [ + { + "key": [ + "dub", + "h1" + ], + "key_as_string": "dub|h1", + "doc_count": 2, + "max-cpu": { + "value": 90.0 + } + }, + { + "key": [ + "dub", + "h2" + ], + "key_as_string": "dub|h2", + "doc_count": 2, + "max-cpu": { + "value": 70.0 + } + }, + { + "key": [ + "iad", + "h2" + ], + "key_as_string": "iad|h2", + "doc_count": 2, + "max-cpu": { + "value": 50.0 + } + }, + { + "key": [ + "iad", + "h1" + ], + "key_as_string": "iad|h1", + "doc_count": 2, + "max-cpu": { + "value": 15.0 + } + } + ] + } + } +} +``` diff --git a/i18n/zh/aggregations/bucket/nested.md b/i18n/zh/aggregations/bucket/nested.md new file mode 100644 index 00000000..44d457e1 --- /dev/null +++ b/i18n/zh/aggregations/bucket/nested.md @@ -0,0 +1,96 @@ +--- +title: 嵌套 +--- + +# 嵌套聚合 + +`nested` 聚合(Aggregation)可以让你对嵌套对象中的字段进行聚合。`nested` 类型是 object 数据类型的一个特殊版本,它允许以一种可以彼此独立查询的方式来索引对象数组 + +使用 `object` 类型时,所有数据都存储在同一个文档(Document)中,因此搜索匹配可能会跨越子文档。例如,假设有一个 `logs` 索引(Index),其中 `pages` 被映射为 `object` 数据类型: + +```json +PUT logs/_doc/0 +{ + "response": "200", + "pages": [ + { + "page": "landing", + "load_time": 200 + }, + { + "page": "blog", + "load_time": 500 + } + ] +} +``` + +OpenSearch 会合并实体关系的所有子属性,结果大致如下: + +```json +{ + "logs": { + "pages": ["landing", "blog"], + "load_time": ["200", "500"] + } +} +``` + +因此,如果你想使用 `pages=landing` 和 `load_time=500` 搜索此索引,即使 landing 的 `load_time` 值为 200,该文档也会匹配条件。 + +如果你想确保不会出现这种跨对象匹配,请将该字段映射为 `nested` 类型: + +```json +PUT logs +{ + "mappings": { + "properties": { + "pages": { + "type": "nested", + "properties": { + "page": { "type": "text" }, + "load_time": { "type": "double" } + } + } + } + } +} +``` + +嵌套文档允许你索引同一个 JSON 文档,但会将各个页面保存在单独的 Lucene 文档中,从而只有 `pages=landing` 和 `load_time=200` 这样的搜索才会返回预期结果。在内部,嵌套对象会将数组中的每个对象索引为一个单独的隐藏文档,这意味着每个嵌套对象都可以独立于其他对象进行查询。 + +你必须指定一个相对于父级的嵌套路径,该路径包含嵌套文档: + +```json +GET logs/_search +{ + "query": { + "match": { "response": "200" } + }, + "aggs": { + "pages": { + "nested": { + "path": "pages" + }, + "aggs": { + "min_load_time": { "min": { "field": "pages.load_time" } } + } + } + } +} +``` + +#### 示例响应 + +```json +... +"aggregations" : { + "pages" : { + "doc_count" : 2, + "min_price" : { + "value" : 200.0 + } + } + } +} +``` diff --git a/i18n/zh/aggregations/bucket/range.md b/i18n/zh/aggregations/bucket/range.md new file mode 100644 index 00000000..8ac22e60 --- /dev/null +++ b/i18n/zh/aggregations/bucket/range.md @@ -0,0 +1,71 @@ +--- +title: 范围 +--- + +# 范围聚合 + +`range` 聚合(Aggregation)可以让你为每个桶(Bucket)定义范围。 + +例如,你可以分别统计字节数介于 1000 到 2000、2000 到 3000 以及 3000 到 4000 之间的数量。 +在 `range` 参数中,你可以将各个范围定义为数组中的对象。 + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "number_of_bytes_distribution": { + "range": { + "field": "bytes", + "ranges": [ + { + "from": 1000, + "to": 2000 + }, + { + "from": 2000, + "to": 3000 + }, + { + "from": 3000, + "to": 4000 + } + ] + } + } + } +} +``` + +响应包含 `from` 键的值,但不包含 `to` 键的值: + +#### 示例响应 + +```json +... +"aggregations" : { + "number_of_bytes_distribution" : { + "buckets" : [ + { + "key" : "1000.0-2000.0", + "from" : 1000.0, + "to" : 2000.0, + "doc_count" : 805 + }, + { + "key" : "2000.0-3000.0", + "from" : 2000.0, + "to" : 3000.0, + "doc_count" : 1369 + }, + { + "key" : "3000.0-4000.0", + "from" : 3000.0, + "to" : 4000.0, + "doc_count" : 1422 + } + ] + } + } +} +``` diff --git a/i18n/zh/aggregations/bucket/reverse-nested.md b/i18n/zh/aggregations/bucket/reverse-nested.md new file mode 100644 index 00000000..bab35e22 --- /dev/null +++ b/i18n/zh/aggregations/bucket/reverse-nested.md @@ -0,0 +1,85 @@ +--- +title: 反向嵌套 +--- + +# 反向嵌套聚合 + +你可以将嵌套文档(Document)中的值聚合到其父文档,这种聚合(Aggregation)称为 `reverse_nested`。 +在按嵌套对象中的字段分组之后,你可以使用 `reverse_nested` 对父文档中的字段进行聚合。`reverse_nested` 聚合会“回连”根页面,并获取每种变体的 `load_time`。 + +`reverse_nested` 聚合是嵌套聚合中的子聚合。它只接受一个名为 `path` 的选项。该选项定义了 OpenSearch 在文档层级中向上回溯多少级来计算聚合。 + +```json +GET logs/_search +{ + "query": { + "match": { "response": "200" } + }, + "aggs": { + "pages": { + "nested": { + "path": "pages" + }, + "aggs": { + "top_pages_per_load_time": { + "terms": { + "field": "pages.load_time" + }, + "aggs": { + "comment_to_logs": { + "reverse_nested": {}, + "aggs": { + "min_load_time": { + "min": { + "field": "pages.load_time" + } + } + } + } + } + } + } + } + } +} +``` + +#### 示例响应 + +```json +... +"aggregations" : { + "pages" : { + "doc_count" : 2, + "top_pages_per_load_time" : { + "doc_count_error_upper_bound" : 0, + "sum_other_doc_count" : 0, + "buckets" : [ + { + "key" : 200.0, + "doc_count" : 1, + "comment_to_logs" : { + "doc_count" : 1, + "min_load_time" : { + "value" : null + } + } + }, + { + "key" : 500.0, + "doc_count" : 1, + "comment_to_logs" : { + "doc_count" : 1, + "min_load_time" : { + "value" : null + } + } + } + ] + } + } + } +} +``` + +响应显示,logs 索引(Index)中有一个页面的 `load_time` 为 200,另一个页面的 `load_time` 为 500。 diff --git a/i18n/zh/aggregations/bucket/sampler.md b/i18n/zh/aggregations/bucket/sampler.md new file mode 100644 index 00000000..5d7c80de --- /dev/null +++ b/i18n/zh/aggregations/bucket/sampler.md @@ -0,0 +1,79 @@ +--- +title: 采样器 +--- + +# 采样器聚合 + +如果你要聚合非常多的文档(Document),可以使用 `sampler` 聚合(Aggregation)将范围缩小到一小部分文档样本,从而加快响应速度。`sampler` 聚合按评分最高的文档来选择样本。 + +结果是近似的,但能够较好地反映真实数据的分布。`sampler` 聚合可以显著提升查询(Query)性能,但估算出的响应并不完全可靠。 + +基本语法如下: + +```json +“aggs”: { + "SAMPLE": { + "sampler": { + "shard_size": 100 + }, + "aggs": {...} + } +} +``` + +## 分片大小属性 + +`shard_size` 属性告诉 OpenSearch 从每个分片(Shard)中(最多)收集多少个文档。 + +以下示例将每个分片上收集的文档数限制为 1,000,然后通过 `terms` 聚合对这些文档进行分桶: + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "sample": { + "sampler": { + "shard_size": 1000 + }, + "aggs": { + "terms": { + "terms": { + "field": "agent.keyword" + } + } + } + } + } +} +``` + +#### 示例响应 + +```json +... +"aggregations" : { + "sample" : { + "doc_count" : 1000, + "terms" : { + "doc_count_error_upper_bound" : 0, + "sum_other_doc_count" : 0, + "buckets" : [ + { + "key" : "Mozilla/5.0 (X11; Linux x86_64; rv:6.0a1) Gecko/20110421 Firefox/6.0a1", + "doc_count" : 368 + }, + { + "key" : "Mozilla/5.0 (X11; Linux i686) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.50 Safari/534.24", + "doc_count" : 329 + }, + { + "key" : "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)", + "doc_count" : 303 + } + ] + } + } + } +} +``` diff --git a/i18n/zh/aggregations/bucket/significant-terms.md b/i18n/zh/aggregations/bucket/significant-terms.md new file mode 100644 index 00000000..270fffe0 --- /dev/null +++ b/i18n/zh/aggregations/bucket/significant-terms.md @@ -0,0 +1,64 @@ +--- +title: 显著词项 +--- + +# 显著词项聚合 + +`significant_terms` 聚合(Aggregation)可以让你发现,相对于索引(Index)中的其余数据,经过过滤的子集中出现了哪些不寻常或值得关注的词项。 + +前景集是你过滤得到的文档(Document)集合,背景集是索引中所有文档的集合。 +`significant_terms` 聚合会检查前景集中的所有文档,并与背景集中的文档进行对比,为显著出现的词项计算评分。 + +在 Web 日志示例数据中,每个文档都有一个包含访问者 `user-agent` 的字段。此示例搜索来自 iOS 操作系统的所有请求。对该前景集执行普通的 `terms` 聚合会返回 Firefox,因为它在这个桶(Bucket)中拥有最多的文档。而 `significant_terms` 聚合则会返回 Internet Explorer(IE),因为与背景集相比,IE 在前景集中出现的频率明显更高。 + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "query": { + "terms": { + "machine.os.keyword": [ + "ios" + ] + } + }, + "aggs": { + "significant_response_codes": { + "significant_terms": { + "field": "agent.keyword" + } + } + } +} +``` + +#### 示例响应 + +```json +... +"aggregations" : { + "significant_response_codes" : { + "doc_count" : 2737, + "bg_count" : 14074, + "buckets" : [ + { + "key" : "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)", + "doc_count" : 818, + "score" : 0.01462731514608217, + "bg_count" : 4010 + }, + { + "key" : "Mozilla/5.0 (X11; Linux x86_64; rv:6.0a1) Gecko/20110421 Firefox/6.0a1", + "doc_count" : 1067, + "score" : 0.009062566630410223, + "bg_count" : 5362 + } + ] + } + } +} +``` + +如果 `significant_terms` 聚合没有返回任何结果,可能是因为你没有使用查询(Query)对结果进行过滤。也可能是前景集中词项的分布与背景集相同,这意味着前景集中没有任何不寻常之处。 + +背景词项频率统计信息的默认来源是整个索引。你可以使用背景过滤器缩小这一范围,使分析更有针对性 diff --git a/i18n/zh/aggregations/bucket/significant-text.md b/i18n/zh/aggregations/bucket/significant-text.md new file mode 100644 index 00000000..94d17948 --- /dev/null +++ b/i18n/zh/aggregations/bucket/significant-text.md @@ -0,0 +1,127 @@ +--- +title: 显著文本 +--- + +# 显著文本聚合 + +`significant_text` 聚合(Aggregation)与 `significant_terms` 聚合类似,但它用于原始文本字段。 +显著文本使用统计分析来衡量前景集与背景集之间流行程度的变化。例如,当你查找股票代码 TSLA 时,它可能会提示 Tesla。 + +`significant_text` 聚合会即时重新分析源文本,过滤掉重复段落、样板式页眉和页脚等噪声数据,否则这些数据可能会使结果产生偏差。 + +重新分析高基数数据集可能是一项非常消耗 CPU 的操作。我们建议在 sampler 聚合中使用 `significant_text` 聚合,将分析限制在少量最匹配的文档(Document)中,例如 200 个。 + +你可以设置以下参数: + +- `min_doc_count` - 返回匹配的热门命中(Hit)数超过所配置数量的结果。我们不建议将 `min_doc_count` 设置为 1,因为这往往会返回拼写错误的词项。找到某个词项的多个实例,有助于确认其显著性并非一次性偶然的结果。默认值 3 用于提供最低限度的证据权重。 +- `shard_size` - 设置较高的值可以提高稳定性(和准确性),但会牺牲计算性能。 +- `shard_min_doc_count` - 如果你的文本包含许多你不关心的低频词(例如拼写错误),可以设置 `shard_min_doc_count` 参数,在分片(Shard)级别过滤掉那些即使合并了本地显著文本频率后,也基本可以确定达不到所需 `min_doc_count` 的候选词项。默认值为 1,在你显式设置之前不会产生任何影响。我们建议将此值设置得远低于 `min_doc_count` 的值。 + +假设你已经将莎士比亚全集索引到 OpenSearch 集群中。你可以在 `text_entry` 字段中查找与单词 "breathe" 相关的显著文本: + +```json +GET shakespeare/_search +{ + "query": { + "match": { + "text_entry": "breathe" + } + }, + "aggregations": { + "my_sample": { + "sampler": { + "shard_size": 100 + }, + "aggregations": { + "keywords": { + "significant_text": { + "field": "text_entry", + "min_doc_count": 4 + } + } + } + } + } +} +``` + +#### 示例响应 + +```json +"aggregations" : { + "my_sample" : { + "doc_count" : 59, + "keywords" : { + "doc_count" : 59, + "bg_count" : 111396, + "buckets" : [ + { + "key" : "breathe", + "doc_count" : 59, + "score" : 1887.0677966101694, + "bg_count" : 59 + }, + { + "key" : "air", + "doc_count" : 4, + "score" : 2.641295376716233, + "bg_count" : 189 + }, + { + "key" : "dead", + "doc_count" : 4, + "score" : 0.9665839666414213, + "bg_count" : 495 + }, + { + "key" : "life", + "doc_count" : 5, + "score" : 0.9090787433467572, + "bg_count" : 805 + } + ] + } + } + } +} +``` + +与 `breathe` 最相关的显著文本是 `air`、`dead` 和 `life`。 + +`significant_text` 聚合有以下限制: + +- 不支持子聚合,因为子聚合的内存开销很高。作为一种变通方法,你可以添加一个后续查询(Query),在其中使用带有 include 子句的 `terms` 聚合和子聚合。 +- 不支持嵌套对象,因为它处理的是文档的 JSON 源数据。 +- 由于文档计数是通过对每个分片返回的样本求和得到的,因此可能存在一些(通常很小的)误差。你可以使用 `shard_size` 参数来微调准确性与性能之间的权衡。默认情况下,`shard_size` 设置为 -1,以自动估算分片数和 `size` 参数。 + +背景词项频率统计信息的默认来源是整个索引(Index)。你可以使用背景过滤器缩小这一范围,使分析更有针对性: + +```json +GET shakespeare/_search +{ + "query": { + "match": { + "text_entry": "breathe" + } + }, + "aggregations": { + "my_sample": { + "sampler": { + "shard_size": 100 + }, + "aggregations": { + "keywords": { + "significant_text": { + "field": "text_entry", + "background_filter": { + "term": { + "speaker": "JOHN OF GAUNT" + } + } + } + } + } + } + } +} +``` diff --git a/i18n/zh/aggregations/bucket/terms.md b/i18n/zh/aggregations/bucket/terms.md new file mode 100644 index 00000000..c2c60a76 --- /dev/null +++ b/i18n/zh/aggregations/bucket/terms.md @@ -0,0 +1,185 @@ +--- +title: 词项 +--- + +# 词项聚合 + +`terms` 聚合(Aggregation)会为字段的每个唯一词项动态创建一个桶(Bucket)。 + +以下示例使用 `terms` 聚合统计 Web 日志数据中每个响应代码对应的文档(Document)数量: + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "response_codes": { + "terms": { + "field": "response.keyword", + "size": 10 + } + } + } +} +``` + +#### 示例响应 + +```json +... +"aggregations" : { + "response_codes" : { + "doc_count_error_upper_bound" : 0, + "sum_other_doc_count" : 0, + "buckets" : [ + { + "key" : "200", + "doc_count" : 12832 + }, + { + "key" : "404", + "doc_count" : 801 + }, + { + "key" : "503", + "doc_count" : 441 + } + ] + } + } +} +``` + +值通过键 `key` 返回。 +`doc_count` 指定每个桶中的文档数。默认情况下,桶按 `doc-count` 降序排列。 + +## size 和 shard_size 参数 + +`terms` 聚合返回的桶数由 `size` 参数控制,默认值为 10。 + +此外,负责聚合的协调节点会向每个分片(Shard)请求其排名靠前的唯一词项。每个分片返回的桶数由 `shard_size` 参数控制。该参数不同于 `size` 参数,其作用是提高桶文档计数的准确性。 + +例如,假设 `size` 和 `shard_size` 参数的值都为 3。`terms` 聚合会向每个分片请求其排名前三的唯一词项,协调节点再对这些结果进行聚合以计算最终结果。如果某个分片包含一个未进入前三的对象,那么它就不会出现在响应中。不过,为该请求增大 `shard_size` 值可以让每个分片返回更多的唯一词项,从而提高协调节点收到所有相关结果的可能性。 + +默认情况下,`shard_size` 参数设置为 `size * 1.5 + 10`。 + +使用并发段搜索时,`shard_size` 参数也会应用于每个段切片。 + +`shard_size` 参数用于在 `terms` 聚合的性能与文档计数准确性之间进行权衡。较高的 `shard_size` 值可以确保更高的文档计数准确性,但会占用更多内存和计算资源。较低的 `shard_size` 值性能更好,但文档计数的准确性较低。 + +## 文档计数误差 + +响应中还包含两个键:`doc_count_error_upper_bound` 和 `sum_other_doc_count`。 + +`terms` 聚合返回排名靠前的唯一词项。因此,如果数据中包含许多唯一词项,其中一些可能不会出现在结果中。`sum_other_doc_count` 字段表示被排除在响应之外的文档总数。在本例中,该数值为 0,因为所有唯一值都出现在了响应中。 + +`doc_count_error_upper_bound` 字段表示被排除在最终结果之外的唯一值可能具有的最大计数。可以使用该字段来估算计数的误差范围。 + +`doc_count_error_upper_bound` 值和准确性的概念仅适用于使用默认排序顺序(即按文档数降序)的聚合。这是因为当你按文档数降序排序时,任何未返回的词项所包含的文档数都必然小于或等于已返回的词项。基于这一点,就可以计算出 `doc_count_error_upper_bound`。 + +如果将 `show_term_doc_count_error` 参数设置为 `true`,则 `terms` 聚合除了显示总体值之外,还会显示为每个唯一桶计算的 `doc_count_error_upper_bound`。 + +## `min_doc_count` 和 `shard_min_doc_count` 参数 {#the-mindoccount-and-shardmindoccount-parameters} + +你可以使用 `min_doc_count` 参数过滤掉结果数少于 `min_doc_count` 的唯一词项。`min_doc_count` 阈值只有在合并了从所有分片检索到的结果之后才会应用。每个分片并不知道给定词项的全局文档计数。如果全局最频繁的前 `shard_size` 个词项与某个分片本地的高频词项之间存在显著差异,那么在使用 `min_doc_count` 参数时可能会得到意外的结果。 + +另外,`shard_min_doc_count` 参数用于过滤掉分片返回给协调节点、但结果数少于 `shard_min_doc_count` 的唯一词项。 + +使用并发段搜索时,`shard_min_doc_count` 参数不会应用于每个段切片。有关更多信息,请参阅[相关 GitHub issue](https://github.com/opensearch-project/OpenSearch/issues/11847)。 + +## 收集模式 + +有两种可用的收集模式:`depth_first` 和 `breadth_first`。`depth_first` 收集模式以深度优先的方式展开聚合树的所有分支,并且只在展开完成之后才进行剪枝。 + +然而,在使用嵌套的 `terms` 聚合时,返回的桶数基数会与每一层嵌套中字段的基数相乘,因此随着聚合的嵌套,桶数很容易出现组合爆炸。 + +你可以使用 `breadth_first` 收集模式来解决这个问题。在这种模式下,聚合树的第一层会在展开到下一层之前先进行剪枝,这可能会大幅减少需要计算的桶数。 + +此外,执行 `breadth_first` 收集会带来一定的内存开销,该开销与匹配文档的数量呈线性关系。这是因为 `breadth_first` 收集的工作方式是缓存并重放来自父级的、经过剪枝的桶集合。 + +## 处理预聚合数据 + +虽然 `doc_count` 字段表示聚合到某个桶中的单个文档数量,但 `doc_count` 本身无法正确地累加存储了预聚合数据的文档。为了处理预聚合数据并准确计算桶中的文档数,你可以使用 `_doc_count` 字段,在单个汇总字段中添加文档数量。当文档包含 `_doc_count` 字段时,所有桶聚合(Bucket Aggregation)都会识别其值,并累加到桶的 `doc_count` 中。使用 `_doc_count` 字段时请注意以下事项: + +* 该字段不支持嵌套数组,只能使用正整数。 +* 如果文档不包含 `_doc_count` 字段,聚合会将该文档计为 1。 + +::: tip 提示 +那些依赖准确文档计数的 OpenSearch 功能体现了使用 `_doc_count` 字段的重要性。要了解如何使用该字段来支持其他搜索工具,请参阅[索引汇总(Index rollups)](https://opensearch.org/docs/latest/im-plugin/index-rollups/index/)。这是索引管理(Index Management,IM)插件中的一项 OpenSearch 功能,它会将包含预聚合数据的文档存储在汇总索引中。 +::: + +#### 示例请求 + +```json +PUT /my_index/_doc/1 +{ + "response_code": 404, + "date":"2022-08-05", + "_doc_count": 20 +} + +PUT /my_index/_doc/2 +{ + "response_code": 404, + "date":"2022-08-06", + "_doc_count": 10 +} + +PUT /my_index/_doc/3 +{ + "response_code": 200, + "date":"2022-08-06", + "_doc_count": 300 +} + +GET /my_index/_search +{ + "size": 0, + "aggs": { + "response_codes": { + "terms": { + "field" : "response_code" + } + } + } +} +``` + +#### 示例响应 {#example-response-1} + +```json +{ + "took" : 20, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 3, + "relation" : "eq" + }, + "max_score" : null, + "hits" : [ ] + }, + "aggregations" : { + "response_codes" : { + "doc_count_error_upper_bound" : 0, + "sum_other_doc_count" : 0, + "buckets" : [ + { + "key" : 200, + "doc_count" : 300 + }, + { + "key" : 404, + "doc_count" : 30 + } + ] + } + } +} +``` diff --git a/i18n/zh/aggregations/index.md b/i18n/zh/aggregations/index.md new file mode 100644 index 00000000..dbe83158 --- /dev/null +++ b/i18n/zh/aggregations/index.md @@ -0,0 +1,159 @@ +--- +title: 聚合 +--- + +# 聚合 + +OpenSearch 不只是用于搜索。借助聚合(Aggregation),你可以利用 OpenSearch 强大的分析引擎来分析数据并从中提取统计信息。 + +聚合的用例多种多样,从实时分析数据以便采取行动,到使用 OpenSearch Dashboards 创建可视化仪表板,不一而足。 + +OpenSearch 可以在几毫秒内对海量数据集执行聚合。与查询(Query)相比,聚合会消耗更多的 CPU 周期和内存。 + +## 对 text 字段执行聚合 + +默认情况下,OpenSearch 不支持对 text 字段执行聚合。由于 text 字段会被分词,对 text 字段执行聚合时必须先逆转分词过程、还原出原始字符串,然后再基于该字符串进行聚合。这类操作会消耗大量内存并降低集群性能。 + +虽然你可以在映射(Mapping)中将 `fielddata` 参数设置为 `true` 来启用对 text 字段的聚合,但聚合仍然基于分词后的单词,而不是原始文本。 + +我们建议将 text 字段的原始版本保留为一个 `keyword` 字段,以便对其执行聚合。 + +在这种情况下,你可以对 `title.raw` 字段而不是 `title` 字段执行聚合: + +```json +PUT movies +{ + "mappings": { + "properties": { + "title": { + "type": "text", + "fielddata": true, + "fields": { + "raw": { + "type": "keyword" + } + } + } + } + } +} +``` + +## 聚合的通用结构 + +聚合查询的结构如下: + +```json +GET _search +{ + "size": 0, + "aggs": { + "NAME": { + "AGG_TYPE": {} + } + } +} +``` + +如果你只关心聚合结果而不关心查询结果,请将 `size` 设置为 0。 + +在 `aggs` 属性中(也可以使用 `aggregations`),你可以定义任意数量的聚合。每个聚合都由其名称和 OpenSearch 所支持的某种聚合类型来定义。 + +聚合名称可以帮助你在响应中区分不同的聚合。`AGG_TYPE` 属性用于指定聚合的类型。 + +## 聚合示例 + +本节使用 OpenSearch Dashboards 的电子商务示例数据和 Web 日志示例数据。要添加示例数据,请登录 OpenSearch Dashboards,选择 **Home**,然后选择 **Try our sample data**。对于 **Sample eCommerce orders** 和 **Sample web logs**,选择 **Add data**。 + +### avg + +查找 `taxful_total_price` 字段的平均值: + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "avg_taxful_total_price": { + "avg": { + "field": "taxful_total_price" + } + } + } +} +``` + +#### 示例响应 + +```json +{ + "took" : 1, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 4675, + "relation" : "eq" + }, + "max_score" : null, + "hits" : [ ] + }, + "aggregations" : { + "avg_taxful_total_price" : { + "value" : 75.05542864304813 + } + } +} +``` + +响应中的聚合块显示了 `taxful_total_price` 字段的平均值。 + +## 聚合类型 + +聚合主要有三种类型: + +- 指标聚合(Metric Aggregation)——对数值字段计算 `sum`、`min`、`max` 和 `avg` 等指标。 +- 桶聚合(Bucket Aggregation)——根据某些条件将查询结果分组。 +- 管道聚合(Pipeline Aggregation)——将一个聚合的输出作为另一个聚合的输入。 + +## 嵌套聚合 + +聚合中的聚合称为嵌套聚合或子聚合(subaggregation)。 + +指标聚合产生简单的结果,不能包含嵌套聚合。 + +桶聚合会产生由文档(Document)组成的桶(Bucket),你可以将其嵌套在其他聚合中。通过在桶聚合中嵌套指标聚合和桶聚合,你可以对数据执行复杂的分析。 + +### 嵌套聚合的通用语法 + +```json +{ + "aggs": { + "name": { + "type": { + "data" + }, + "aggs": { + "nested": { + "type": { + "data" + } + } + } + } + } +} +``` + +内层的 `aggs` 关键字开始一个新的嵌套聚合。父聚合和嵌套聚合的语法相同。嵌套聚合在其前面的父聚合的上下文中运行。 + +你还可以将聚合与搜索查询结合使用,在聚合之前缩小要分析的范围。如果你不添加查询,OpenSearch 会隐式使用 `match_all` 查询。 + +## 限制 + +由于聚合器对所有值都使用 `double` 数据类型进行处理,因此大于等于 253 的 `long` 值是近似值。 diff --git a/i18n/zh/aggregations/metric/average.md b/i18n/zh/aggregations/metric/average.md new file mode 100644 index 00000000..b9bd1801 --- /dev/null +++ b/i18n/zh/aggregations/metric/average.md @@ -0,0 +1,51 @@ +--- +title: 平均值 +--- + +# 平均值聚合 + +`avg` 指标是一种单值指标聚合(Metric Aggregation),返回字段的平均值。 + +以下示例计算 `taxful_total_price` 字段的平均值: + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "avg_taxful_total_price": { + "avg": { + "field": "taxful_total_price" + } + } + } +} +``` + +#### 示例响应 + +```json +{ + "took": 85, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "avg_taxful_total_price": { + "value": 75.05542864304813 + } + } +} +``` diff --git a/i18n/zh/aggregations/metric/cardinality.md b/i18n/zh/aggregations/metric/cardinality.md new file mode 100644 index 00000000..0958936e --- /dev/null +++ b/i18n/zh/aggregations/metric/cardinality.md @@ -0,0 +1,55 @@ +--- +title: 基数 +--- + +# 基数聚合 + +`cardinality` 指标是一种单值指标聚合(Metric Aggregation),用于统计字段中唯一值(即不同值)的数量。 + +以下示例查找电子商务商店中不同产品的数量: + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "unique_products": { + "cardinality": { + "field": "products.product_id" + } + } + } +} +``` + +#### 示例响应 + +```json +... + "aggregations" : { + "unique_products" : { + "value" : 7033 + } + } +} +``` + +基数计数是近似值。 +如果你假想的商店中有数万种产品,精确计算基数就需要将所有值加载到一个哈希集合中,并返回该集合的大小。这种方法的可扩展性很差,它需要占用大量内存,并可能导致很高的延迟。 + +你可以通过 `precision_threshold` 设置来控制内存与准确性之间的权衡。该设置定义了一个阈值,低于此阈值时,计数预计会接近精确值;高于此值时,计数的准确性可能会有所下降。`precision_threshold` 的默认值为 3,000,支持的最大值为 40,000。 + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "unique_products": { + "cardinality": { + "field": "products.product_id", + "precision_threshold": 10000 + } + } + } +} +``` diff --git a/i18n/zh/aggregations/metric/extended-stats.md b/i18n/zh/aggregations/metric/extended-stats.md new file mode 100644 index 00000000..cbd8162d --- /dev/null +++ b/i18n/zh/aggregations/metric/extended-stats.md @@ -0,0 +1,70 @@ +--- +title: 扩展统计 +--- + +# 扩展统计聚合 + +`extended_stats` 聚合(Aggregation)是 [`stats`](/aggregations/metric/stats) 聚合的扩展版本。除了基本统计信息外,`extended_stats` 还会返回 `sum_of_squares`、`variance` 和 `std_deviation` 等统计信息。 +以下示例返回 `taxful_total_price` 的扩展统计信息: +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "extended_stats_taxful_total_price": { + "extended_stats": { + "field": "taxful_total_price" + } + } + } +} +``` + +#### 示例响应 + +```json +... +"aggregations" : { + "extended_stats_taxful_total_price" : { + "count" : 4675, + "min" : 6.98828125, + "max" : 2250.0, + "avg" : 75.05542864304813, + "sum" : 350884.12890625, + "sum_of_squares" : 3.9367749294174194E7, + "variance" : 2787.59157113862, + "variance_population" : 2787.59157113862, + "variance_sampling" : 2788.187974983536, + "std_deviation" : 52.79764740155209, + "std_deviation_population" : 52.79764740155209, + "std_deviation_sampling" : 52.80329511482722, + "std_deviation_bounds" : { + "upper" : 180.6507234461523, + "lower" : -30.53986616005605, + "upper_population" : 180.6507234461523, + "lower_population" : -30.53986616005605, + "upper_sampling" : 180.66201887270256, + "lower_sampling" : -30.551161586606312 + } + } + } +} +``` + +`std_deviation_bounds` 对象以均值上下各两个标准差为区间,直观地呈现数据的离散程度。 +要将标准差设置为其他值(例如 3),请将 `sigma` 设置为 3: + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "extended_stats_taxful_total_price": { + "extended_stats": { + "field": "taxful_total_price", + "sigma": 3 + } + } + } +} +``` diff --git a/i18n/zh/aggregations/metric/geobounds.md b/i18n/zh/aggregations/metric/geobounds.md new file mode 100644 index 00000000..b4ab8abc --- /dev/null +++ b/i18n/zh/aggregations/metric/geobounds.md @@ -0,0 +1,218 @@ +--- +title: 地理边界 +--- + +## 地理边界聚合 + +`geo_bounds` 指标是一种多值指标聚合(Metric Aggregation),用于计算包含给定 `geo_point` 或 `geo_shape` 字段所有值的[地理边界框](https://docs.ogc.org/is/12-063r5/12-063r5.html#30)。边界框以矩形左上角和右下角顶点的经纬度形式返回。 + +以下示例返回 `geoip.location` 字段的 `geo_bounds` 指标: + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "geo": { + "geo_bounds": { + "field": "geoip.location" + } + } + } +} +``` + +#### 示例响应 + +```json +"aggregations" : { + "geo" : { + "bounds" : { + "top_left" : { + "lat" : 52.49999997206032, + "lon" : -118.20000001229346 + }, + "bottom_right" : { + "lat" : 4.599999985657632, + "lon" : 55.299999956041574 + } + } + } + } +} +``` + +## 聚合 geoshape + +要对 geoshape 字段执行聚合,首先创建一个索引(Index),并将 `location` 字段映射为 `geo_shape`: + +```json +PUT national_parks +{ + "mappings": { + "properties": { + "location": { + "type": "geo_shape" + } + } + } +} +``` + +接下来,向 `national_parks` 索引中索引一些文档(Document): + +```json +PUT national_parks/_doc/1 +{ + "name": "Yellowstone National Park", + "location": + {"type": "envelope","coordinates": [ [-111.15, 45.12], [-109.83, 44.12] ]} +} +``` + +```json +PUT national_parks/_doc/2 +{ + "name": "Yosemite National Park", + "location": + {"type": "envelope","coordinates": [ [-120.23, 38.16], [-119.05, 37.45] ]} +} +``` + +```json +PUT national_parks/_doc/3 +{ + "name": "Death Valley National Park", + "location": + {"type": "envelope","coordinates": [ [-117.34, 37.01], [-116.38, 36.25] ]} +} +``` + +你可以按如下方式对 `location` 字段执行 `geo_bounds` 聚合: + +```json +GET national_parks/_search +{ + "aggregations": { + "grouped": { + "geo_bounds": { + "field": "location", + "wrap_longitude": true + } + } + } +} +``` + +可选参数 `wrap_longitude` 指定聚合返回的边界框是否可以跨越国际日期变更线(180° 经线)。如果将 `wrap_longitude` 设置为 `true`,边界框就可以跨越国际日期变更线,并返回一个左下角经度大于右上角经度的 `bounds` 对象。`wrap_longitude` 的默认值为 `true`。 + +响应中包含能够包围 `location` 字段中所有形状的地理边界框: + +
+ + 响应 + + +```json +{ + "took" : 3, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 3, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "national_parks", + "_id" : "1", + "_score" : 1.0, + "_source" : { + "name" : "Yellowstone National Park", + "location" : { + "type" : "envelope", + "coordinates" : [ + [ + -111.15, + 45.12 + ], + [ + -109.83, + 44.12 + ] + ] + } + } + }, + { + "_index" : "national_parks", + "_id" : "2", + "_score" : 1.0, + "_source" : { + "name" : "Yosemite National Park", + "location" : { + "type" : "envelope", + "coordinates" : [ + [ + -120.23, + 38.16 + ], + [ + -119.05, + 37.45 + ] + ] + } + } + }, + { + "_index" : "national_parks", + "_id" : "3", + "_score" : 1.0, + "_source" : { + "name" : "Death Valley National Park", + "location" : { + "type" : "envelope", + "coordinates" : [ + [ + -117.34, + 37.01 + ], + [ + -116.38, + 36.25 + ] + ] + } + } + } + ] + }, + "aggregations" : { + "Grouped" : { + "bounds" : { + "top_left" : { + "lat" : 45.11999997776002, + "lon" : -120.23000006563962 + }, + "bottom_right" : { + "lat" : 36.249999976716936, + "lon" : -109.83000006526709 + } + } + } + } +} +``` +
+ +::: info 注意 +目前,OpenSearch 支持通过 API 执行 geoshape 聚合,但 OpenSearch Dashboards 可视化尚不支持。如果你希望在可视化中实现 geoshape 聚合,请为相关的 [GitHub issue](https://github.com/opensearch-project/dashboards-maps/issues/250) 投票。 +::: diff --git a/i18n/zh/aggregations/metric/index.md b/i18n/zh/aggregations/metric/index.md new file mode 100644 index 00000000..54801f60 --- /dev/null +++ b/i18n/zh/aggregations/metric/index.md @@ -0,0 +1,38 @@ +--- +title: 指标聚合 +--- + +# 指标聚合 + +指标聚合(Metric Aggregation)可以让你执行简单的计算,例如求字段的最小值、最大值和平均值。 + +## 指标聚合的类型 + +指标聚合分为两种类型:单值指标聚合和多值指标聚合。 + +### 单值指标聚合 + +单值指标聚合返回单个指标,例如 `sum`、`min`、`max`、`avg`、`cardinality` 或 `value_count`。 + +### 多值指标聚合 + +多值指标聚合返回多个指标,包括 `stats`、`extended_stats`、`matrix_stats`、`percentile`、`percentile_ranks`、`geo_bound`、`top_hits` 和 `scripted_metric`。 + +## 支持的指标聚合 + +OpenSearch 支持以下指标聚合: + +- [平均值(Average)](/aggregations/metric/average) +- [基数(Cardinality)](/aggregations/metric/cardinality) +- [扩展统计(Extended stats)](/aggregations/metric/extended-stats) +- [地理边界(Geobounds)](/aggregations/metric/geobounds) +- [矩阵统计(Matrix stats)](/aggregations/metric/matrix-stats) +- [最大值(Maximum)](/aggregations/metric/maximum) +- [最小值(Minimum)](/aggregations/metric/minimum) +- [百分位排名(Percentile ranks)](/aggregations/metric/percentile-ranks) +- [百分位数(Percentile)](/aggregations/metric/percentile) +- [脚本指标(Scripted metric)](/aggregations/metric/scripted-metric) +- [统计(Stats)](/aggregations/metric/stats) +- [求和(Sum)](/aggregations/metric/sum) +- [热门命中(Top hits)](/aggregations/metric/top-hits) +- [值计数(Value count)](/aggregations/metric/value-count) diff --git a/i18n/zh/aggregations/metric/matrix-stats.md b/i18n/zh/aggregations/metric/matrix-stats.md new file mode 100644 index 00000000..b6e5e214 --- /dev/null +++ b/i18n/zh/aggregations/metric/matrix-stats.md @@ -0,0 +1,80 @@ +--- +title: 矩阵统计 +--- + +# 矩阵统计聚合 + +`matrix_stats` 聚合(Aggregation)以矩阵形式为多个字段生成高级统计信息。 +以下示例以矩阵形式返回 `taxful_total_price` 和 `products.base_price` 字段的高级统计信息: + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "matrix_stats_taxful_total_price": { + "matrix_stats": { + "fields": ["taxful_total_price", "products.base_price"] + } + } + } +} +``` + +#### 示例响应 + +```json +... +"aggregations" : { + "matrix_stats_taxful_total_price" : { + "doc_count" : 4675, + "fields" : [ + { + "name" : "products.base_price", + "count" : 4675, + "mean" : 34.994239430147196, + "variance" : 360.5035285833703, + "skewness" : 5.530161335032702, + "kurtosis" : 131.16306324042148, + "covariance" : { + "products.base_price" : 360.5035285833703, + "taxful_total_price" : 846.6489362233166 + }, + "correlation" : { + "products.base_price" : 1.0, + "taxful_total_price" : 0.8444765264325268 + } + }, + { + "name" : "taxful_total_price", + "count" : 4675, + "mean" : 75.05542864304839, + "variance" : 2788.1879749835402, + "skewness" : 15.812149139924037, + "kurtosis" : 619.1235507385902, + "covariance" : { + "products.base_price" : 846.6489362233166, + "taxful_total_price" : 2788.1879749835402 + }, + "correlation" : { + "products.base_price" : 0.8444765264325268, + "taxful_total_price" : 1.0 + } + } + ] + } + } +} +``` + +下表列出了所有响应字段。 + +统计项 | 描述 +:--- | :--- +`count` | 测量的样本数量。 +`mean` | 从样本中测得的字段平均值。 +`variance` | 所测字段的值偏离其平均值的程度。方差越大,值偏离平均值的程度就越大。 +`skewness` | 衡量字段值在平均值周围分布的不对称程度。 +`kurtosis` | 衡量分布尾部厚度的指标。尾部越轻,峰度越小;尾部越重,峰度越大。要了解有关峰度的信息,请参阅 [Wikipedia](https://en.wikipedia.org/wiki/Kurtosis)。 +`covariance` | 衡量两个字段之间联合变化程度的指标。正值表示它们的值朝同一方向变化,负值则相反。 +`correlation` | 衡量两个字段之间关系强度的指标。有效值介于 [-1, 1] 之间。值为 -1 表示负相关,值为 1 表示正相关,值为 0 表示二者之间不存在可识别的关系。 diff --git a/i18n/zh/aggregations/metric/maximum.md b/i18n/zh/aggregations/metric/maximum.md new file mode 100644 index 00000000..82a4a7f0 --- /dev/null +++ b/i18n/zh/aggregations/metric/maximum.md @@ -0,0 +1,51 @@ +--- +title: 最大值 +--- + +# 最大值聚合 + +`max` 指标是一种单值指标聚合(Metric Aggregation),返回字段的最大值。 + +以下示例计算 `taxful_total_price` 字段的最大值: + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "max_taxful_total_price": { + "max": { + "field": "taxful_total_price" + } + } + } +} +``` + +#### 示例响应 + +```json +{ + "took": 17, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "max_taxful_total_price": { + "value": 2250 + } + } +} +``` diff --git a/i18n/zh/aggregations/metric/minimum.md b/i18n/zh/aggregations/metric/minimum.md new file mode 100644 index 00000000..0ebc1a9d --- /dev/null +++ b/i18n/zh/aggregations/metric/minimum.md @@ -0,0 +1,51 @@ +--- +title: 最小值 +--- + +# 最小值聚合 + +`min` 指标是一种单值指标聚合(Metric Aggregation),返回字段的最小值。 + +以下示例计算 `taxful_total_price` 字段的最小值: + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "min_taxful_total_price": { + "min": { + "field": "taxful_total_price" + } + } + } +} +``` + +#### 示例响应 + +```json +{ + "took": 13, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "min_taxful_total_price": { + "value": 6.98828125 + } + } +} +``` diff --git a/i18n/zh/aggregations/metric/percentile-ranks.md b/i18n/zh/aggregations/metric/percentile-ranks.md new file mode 100644 index 00000000..52e4ed12 --- /dev/null +++ b/i18n/zh/aggregations/metric/percentile-ranks.md @@ -0,0 +1,40 @@ +--- +title: 百分位排名 +--- + +# 百分位排名聚合 + +百分位排名是指按指定值分组时,小于或等于某个阈值的值所处的百分位。例如,如果某个值大于或等于 80% 的值,则其百分位排名为 80。 + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "percentile_rank_taxful_total_price": { + "percentile_ranks": { + "field": "taxful_total_price", + "values": [ + 10, + 15 + ] + } + } + } +} +``` + +#### 示例响应 + +```json +... +"aggregations" : { + "percentile_rank_taxful_total_price" : { + "values" : { + "10.0" : 0.055096056411283456, + "15.0" : 0.0830092961834656 + } + } + } +} +``` diff --git a/i18n/zh/aggregations/metric/percentile.md b/i18n/zh/aggregations/metric/percentile.md new file mode 100644 index 00000000..84c09198 --- /dev/null +++ b/i18n/zh/aggregations/metric/percentile.md @@ -0,0 +1,47 @@ +--- +title: 百分位数 +--- + +# 百分位数聚合 + +百分位数是指小于或等于某个阈值的数据所占的百分比。 + +`percentile` 指标是一种多值指标聚合(Metric Aggregation),可以帮助你找出数据中的离群值或了解数据的分布情况。 + +与 `cardinality` 指标一样,`percentile` 指标也是近似值。 + +以下示例计算 `taxful_total_price` 字段的百分位数: + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "percentile_taxful_total_price": { + "percentiles": { + "field": "taxful_total_price" + } + } + } +} +``` + +#### 示例响应 + +```json +... +"aggregations" : { + "percentile_taxful_total_price" : { + "values" : { + "1.0" : 21.984375, + "5.0" : 27.984375, + "25.0" : 44.96875, + "50.0" : 64.22061688311689, + "75.0" : 93.0, + "95.0" : 156.0, + "99.0" : 222.0 + } + } + } +} +``` diff --git a/i18n/zh/aggregations/metric/scripted-metric.md b/i18n/zh/aggregations/metric/scripted-metric.md new file mode 100644 index 00000000..27271760 --- /dev/null +++ b/i18n/zh/aggregations/metric/scripted-metric.md @@ -0,0 +1,66 @@ +--- +title: 脚本指标 +--- + +# 脚本指标聚合 + +`scripted_metric` 指标是一种多值指标聚合(Metric Aggregation),返回根据指定脚本计算出的指标。 + +脚本分为四个阶段:初始阶段、映射(map)阶段、合并(combine)阶段和归约(reduce)阶段。 + +* `init_script`:(可选)设置初始状态,在收集任何文档(Document)之前执行。 +* `map_script`:检查 `type` 字段的值,并对收集到的文档执行聚合。 +* `combine_script`:聚合从每个分片(Shard)返回的状态,并将聚合后的值返回给协调节点。 +* `reduce_script`:提供对变量状态的访问;该变量将每个分片上 `combine_script` 的结果合并为一个数组。 + +以下示例对 Web 日志数据中不同的 HTTP 响应类型进行聚合: + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggregations": { + "responses.counts": { + "scripted_metric": { + "init_script": "state.responses = ['error':0L,'success':0L,'other':0L]", + "map_script": """ + def code = doc['response.keyword'].value; + if (code.startsWith('5') || code.startsWith('4')) { + state.responses.error += 1 ; + } else if(code.startsWith('2')) { + state.responses.success += 1; + } else { + state.responses.other += 1; + } + """, + "combine_script": "state.responses", + "reduce_script": """ + def counts = ['error': 0L, 'success': 0L, 'other': 0L]; + for (responses in states) { + counts.error += responses['error']; + counts.success += responses['success']; + counts.other += responses['other']; + } + return counts; + """ + } + } + } +} +``` + +#### 示例响应 + +```json +... +"aggregations" : { + "responses.counts" : { + "value" : { + "other" : 0, + "success" : 12832, + "error" : 1242 + } + } + } +} +``` diff --git a/i18n/zh/aggregations/metric/stats.md b/i18n/zh/aggregations/metric/stats.md new file mode 100644 index 00000000..b929e54f --- /dev/null +++ b/i18n/zh/aggregations/metric/stats.md @@ -0,0 +1,39 @@ +--- +title: 统计 +--- + +# 统计聚合 + +`stats` 指标是一种多值指标聚合(Metric Aggregation),在一次聚合查询中返回 `min`、`max`、`sum`、`avg` 和 `value_count` 等所有基本指标。 + +以下示例返回 `taxful_total_price` 字段的基本统计信息: + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "stats_taxful_total_price": { + "stats": { + "field": "taxful_total_price" + } + } + } +} +``` + +#### 示例响应 + +```json +... +"aggregations" : { + "stats_taxful_total_price" : { + "count" : 4675, + "min" : 6.98828125, + "max" : 2250.0, + "avg" : 75.05542864304813, + "sum" : 350884.12890625 + } + } +} +``` diff --git a/i18n/zh/aggregations/metric/sum.md b/i18n/zh/aggregations/metric/sum.md new file mode 100644 index 00000000..486c149b --- /dev/null +++ b/i18n/zh/aggregations/metric/sum.md @@ -0,0 +1,51 @@ +--- +title: 求和 +--- + +# 求和聚合 + +`sum` 指标是一种单值指标聚合(Metric Aggregation),返回字段值的总和。 + +以下示例计算 `taxful_total_price` 字段的总和: + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "sum_taxful_total_price": { + "sum": { + "field": "taxful_total_price" + } + } + } +} +``` + +#### 示例响应 + +```json +{ + "took": 16, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "sum_taxful_total_price": { + "value": 350884.12890625 + } + } +} +``` diff --git a/i18n/zh/aggregations/metric/top-hits.md b/i18n/zh/aggregations/metric/top-hits.md new file mode 100644 index 00000000..e8085042 --- /dev/null +++ b/i18n/zh/aggregations/metric/top-hits.md @@ -0,0 +1,142 @@ +--- +title: 热门命中 +--- + +# 热门命中聚合 + +`top_hits` 指标是一种多值指标聚合(Metric Aggregation),它根据被聚合字段的相关性评分(Relevance Score)对匹配的文档(Document)进行排序。 + +你可以指定以下选项: + +- `from`:命中(Hit)的起始位置。 +- `size`:要返回的最大命中数。默认值为 3。 +- `sort`:匹配命中的排序方式。默认情况下,命中按聚合查询的相关性评分排序。 + +以下示例返回电子商务数据中排名前 5 的产品: + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "top_hits_products": { + "top_hits": { + "size": 5 + } + } + } +} +``` + +#### 示例响应 + +```json +... +"aggregations" : { + "top_hits_products" : { + "hits" : { + "total" : { + "value" : 4675, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "opensearch_dashboards_sample_data_ecommerce", + "_type" : "_doc", + "_id" : "glMlwXcBQVLeQPrkHPtI", + "_score" : 1.0, + "_source" : { + "category" : [ + "Women's Accessories", + "Women's Clothing" + ], + "currency" : "EUR", + "customer_first_name" : "rania", + "customer_full_name" : "rania Evans", + "customer_gender" : "FEMALE", + "customer_id" : 24, + "customer_last_name" : "Evans", + "customer_phone" : "", + "day_of_week" : "Sunday", + "day_of_week_i" : 6, + "email" : "rania@evans-family.zzz", + "manufacturer" : [ + "Tigress Enterprises" + ], + "order_date" : "2021-02-28T14:16:48+00:00", + "order_id" : 583581, + "products" : [ + { + "base_price" : 10.99, + "discount_percentage" : 0, + "quantity" : 1, + "manufacturer" : "Tigress Enterprises", + "tax_amount" : 0, + "product_id" : 19024, + "category" : "Women's Accessories", + "sku" : "ZO0082400824", + "taxless_price" : 10.99, + "unit_discount_amount" : 0, + "min_price" : 5.17, + "_id" : "sold_product_583581_19024", + "discount_amount" : 0, + "created_on" : "2016-12-25T14:16:48+00:00", + "product_name" : "Snood - white/grey/peach", + "price" : 10.99, + "taxful_price" : 10.99, + "base_unit_price" : 10.99 + }, + { + "base_price" : 32.99, + "discount_percentage" : 0, + "quantity" : 1, + "manufacturer" : "Tigress Enterprises", + "tax_amount" : 0, + "product_id" : 19260, + "category" : "Women's Clothing", + "sku" : "ZO0071900719", + "taxless_price" : 32.99, + "unit_discount_amount" : 0, + "min_price" : 17.15, + "_id" : "sold_product_583581_19260", + "discount_amount" : 0, + "created_on" : "2016-12-25T14:16:48+00:00", + "product_name" : "Cardigan - grey", + "price" : 32.99, + "taxful_price" : 32.99, + "base_unit_price" : 32.99 + } + ], + "sku" : [ + "ZO0082400824", + "ZO0071900719" + ], + "taxful_total_price" : 43.98, + "taxless_total_price" : 43.98, + "total_quantity" : 2, + "total_unique_products" : 2, + "type" : "order", + "user" : "rani", + "geoip" : { + "country_iso_code" : "EG", + "location" : { + "lon" : 31.3, + "lat" : 30.1 + }, + "region_name" : "Cairo Governorate", + "continent_name" : "Africa", + "city_name" : "Cairo" + }, + "event" : { + "dataset" : "sample_ecommerce" + } + } + ... + } + ] + } + } + } +} +``` diff --git a/i18n/zh/aggregations/metric/value-count.md b/i18n/zh/aggregations/metric/value-count.md new file mode 100644 index 00000000..962c796a --- /dev/null +++ b/i18n/zh/aggregations/metric/value-count.md @@ -0,0 +1,35 @@ +--- +title: 值计数 +--- + +# 值计数聚合 + +`value_count` 指标是一种单值指标聚合(Metric Aggregation),用于计算聚合所基于的值的数量。 + +例如,你可以将 `value_count` 指标与 `avg` 指标一起使用,以确定聚合在计算平均值时使用了多少个数值。 + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "number_of_values": { + "value_count": { + "field": "taxful_total_price" + } + } + } +} +``` + +#### 示例响应 + +```json +... + "aggregations" : { + "number_of_values" : { + "value" : 4675 + } + } +} +``` diff --git a/i18n/zh/aggregations/pipeline-agg.md b/i18n/zh/aggregations/pipeline-agg.md new file mode 100644 index 00000000..868006d9 --- /dev/null +++ b/i18n/zh/aggregations/pipeline-agg.md @@ -0,0 +1,1251 @@ +--- +title: 管道聚合 +--- + +# 管道聚合 + +通过管道聚合(Pipeline Aggregation),你可以把一个聚合(Aggregation)的结果作为输入传递给另一个聚合,从而将多个聚合串联起来,得到更精细的输出。 + +你可以使用管道聚合来计算复杂的统计和数学指标,例如导数、移动平均值、累积和等。 + +## 管道聚合语法 + +管道聚合使用 `buckets_path` 属性来访问其他聚合的结果。 +`buckets_path` 属性具有特定的语法: + +``` +buckets_path = [,]*[, ]; +``` + +其中: + +- `AGG_NAME` 是聚合的名称。 +- `AGG_SEPARATOR` 用于分隔聚合,用 `>` 表示。 +- `METRIC_SEPARATOR` 用于分隔聚合及其指标,用 `.` 表示。 +- `METRIC` 是指标的名称,适用于多值指标聚合(Metric Aggregation)。 + +例如,`my_sum.sum` 选择名为 `my_sum` 的聚合的 `sum` 指标。`popular_tags>my_sum.sum` 将 `my_sum.sum` 嵌套到 `popular_tags` 聚合中。 + +你还可以指定以下附加参数: + +- `gap_policy`:真实数据中可能存在空缺或 null 值。你可以通过 `gap_policy` 属性指定处理这类缺失数据的策略。可以将 `gap_policy` 属性设置为 `skip`,跳过缺失数据并从下一个可用值继续;也可以设置为 `insert_zeros`,用零替换缺失值并继续运行。 +- `format`:输出值的格式类型。例如,日期值可以使用 `yyyy-MM-dd`。 + +## 快速示例 + +对 `sum_total_memory` 聚合返回的所有桶(Bucket)求和: + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "number_of_bytes": { + "histogram": { + "field": "bytes", + "interval": 10000 + }, + "aggs": { + "sum_total_memory": { + "sum": { + "field": "phpmemory" + } + } + } + }, + "sum_copies": { + "sum_bucket": { + "buckets_path": "number_of_bytes>sum_total_memory" + } + } + } +} +``` + +#### 示例响应 + +```json +... +"aggregations" : { + "number_of_bytes" : { + "buckets" : [ + { + "key" : 0.0, + "doc_count" : 13372, + "sum_total_memory" : { + "value" : 9.12664E7 + } + }, + { + "key" : 10000.0, + "doc_count" : 702, + "sum_total_memory" : { + "value" : 0.0 + } + } + ] + }, + "sum_copies" : { + "value" : 9.12664E7 + } + } +} +``` + +## 管道聚合的类型 + +管道聚合分为两种类型: + +### 同级聚合 + +同级聚合(Sibling Aggregation)接收嵌套聚合的输出,并在与嵌套桶相同的层级上生成新的桶或新的聚合。 + +同级聚合必须是多桶聚合(即某个字段有多个分组值),并且指标必须是数值。 + +`min_bucket`、`max_bucket`、`sum_bucket` 和 `avg_bucket` 是常见的同级聚合。 + +### 父聚合 + +父聚合(Parent Aggregation)接收外层聚合的输出,并在与现有桶相同的层级上生成新的桶或新的聚合。 + +父聚合必须将 `min_doc_count` 设置为 0(这是 `histogram` 聚合的默认值),并且指定的指标必须是数值。如果 `min_doc_count` 大于 `0`,某些桶会被省略,这可能导致结果不正确。 + +`derivatives` 和 `cumulative_sum` 是常见的父聚合。 + +## avg_bucket, sum_bucket, min_bucket, max_bucket + +`avg_bucket`、`sum_bucket`、`min_bucket` 和 `max_bucket` 聚合是同级聚合,分别计算前一个聚合每个桶中某个指标的平均值、总和、最小值和最大值。 + +以下示例创建一个间隔为一个月的日期直方图。`sum` 子聚合计算每个月所有字节数的总和。最后,`avg_bucket` 聚合使用该总和计算每月的平均字节数: + +```json +POST opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "visits_per_month": { + "date_histogram": { + "field": "@timestamp", + "interval": "month" + }, + "aggs": { + "sum_of_bytes": { + "sum": { + "field": "bytes" + } + } + } + }, + "avg_monthly_bytes": { + "avg_bucket": { + "buckets_path": "visits_per_month>sum_of_bytes" + } + } + } +} +``` + +#### 示例响应 {#example-response-1} + +```json +... +"aggregations" : { + "visits_per_month" : { + "buckets" : [ + { + "key_as_string" : "2020-10-01T00:00:00.000Z", + "key" : 1601510400000, + "doc_count" : 1635, + "sum_of_bytes" : { + "value" : 9400200.0 + } + }, + { + "key_as_string" : "2020-11-01T00:00:00.000Z", + "key" : 1604188800000, + "doc_count" : 6844, + "sum_of_bytes" : { + "value" : 3.8880434E7 + } + }, + { + "key_as_string" : "2020-12-01T00:00:00.000Z", + "key" : 1606780800000, + "doc_count" : 5595, + "sum_of_bytes" : { + "value" : 3.1445055E7 + } + } + ] + }, + "avg_monthly_bytes" : { + "value" : 2.6575229666666668E7 + } + } +} +``` + +同样,你也可以计算每月字节数的 `sum_bucket`、`min_bucket` 和 `max_bucket` 值。 + +## stats_bucket, extended_stats_bucket {#statsbucket-extendedstatsbucket} + +`stats_bucket` 聚合是一种同级聚合,它为前一个聚合的桶返回多种统计值(`count`、`min`、`max`、`avg` 和 `sum`)。 + +以下示例返回嵌套在 `visits_per_month` 聚合中的 `sum_of_bytes` 聚合所返回的桶的基本统计值: + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "visits_per_month": { + "date_histogram": { + "field": "@timestamp", + "interval": "month" + }, + "aggs": { + "sum_of_bytes": { + "sum": { + "field": "bytes" + } + } + } + }, + "stats_monthly_bytes": { + "stats_bucket": { + "buckets_path": "visits_per_month>sum_of_bytes" + } + } + } +} +``` + +#### 示例响应 {#example-response-2} + +```json +... +"stats_monthly_bytes" : { + "count" : 3, + "min" : 9400200.0, + "max" : 3.8880434E7, + "avg" : 2.6575229666666668E7, + "sum" : 7.9725689E7 + } + } +} +``` + +`extended_stats` 聚合是 `stats` 聚合的扩展版本。除了基本统计值之外,`extended_stats` 还提供 `sum_of_squares`、`variance` 和 `std_deviation` 等统计值。 + +#### 示例响应 {#example-response-3} + +```json +"stats_monthly_visits" : { + "count" : 3, + "min" : 9400200.0, + "max" : 3.8880434E7, + "avg" : 2.6575229666666668E7, + "sum" : 7.9725689E7, + "sum_of_squares" : 2.588843392021381E15, + "variance" : 1.5670496550438025E14, + "variance_population" : 1.5670496550438025E14, + "variance_sampling" : 2.3505744825657038E14, + "std_deviation" : 1.251818539183616E7, + "std_deviation_population" : 1.251818539183616E7, + "std_deviation_sampling" : 1.5331583357780447E7, + "std_deviation_bounds" : { + "upper" : 5.161160045033899E7, + "lower" : 1538858.8829943463, + "upper_population" : 5.161160045033899E7, + "lower_population" : 1538858.8829943463, + "upper_sampling" : 5.723839638222756E7, + "lower_sampling" : -4087937.0488942266 + } + } + } +} +``` + +## bucket_script, bucket_selector + +`bucket_script` 聚合是一种父聚合,它执行脚本,对前一个聚合的每个桶进行计算。请确保指标是数值类型,并且返回值也是数值。 + +使用 `script` 参数添加脚本。脚本可以是内联脚本,也可以存放在文件或索引(Index)中。要启用内联脚本,请在 `config` 文件夹下的 `opensearch.yml` 文件中添加以下行: + +```yaml +script.inline: on +``` + +`buckets_path` 属性由多个条目组成。每个条目是一个键和一个值。键是可以在脚本中使用的值的名称。 + +基本语法如下: + +```json +{ + "bucket_script": { + "buckets_path": { + "my_var1": "the_sum", + "my_var2": "the_value_count" + }, + "script": "params.my_var1 / params.my_var2" + } +} +``` + +以下示例对日期直方图生成的桶使用 `sum` 聚合。根据所得的桶值,在 zip 扩展名的上下文中,以 10,000 字节为间隔计算 RAM 百分比: + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "sales_per_month": { + "histogram": { + "field": "bytes", + "interval": "10000" + }, + "aggs": { + "total_ram": { + "sum": { + "field": "machine.ram" + } + }, + "ext-type": { + "filter": { + "term": { + "extension.keyword": "zip" + } + }, + "aggs": { + "total_ram": { + "sum": { + "field": "machine.ram" + } + } + } + }, + "ram-percentage": { + "bucket_script": { + "buckets_path": { + "machineRam": "ext-type>total_ram", + "totalRam": "total_ram" + }, + "script": "params.machineRam / params.totalRam" + } + } + } + } + } +} +``` + +#### 示例响应 {#example-response-4} + +```json +"aggregations" : { + "sales_per_month" : { + "buckets" : [ + { + "key" : 0.0, + "doc_count" : 13372, + "os-type" : { + "doc_count" : 1558, + "total_ram" : { + "value" : 2.0090783268864E13 + } + }, + "total_ram" : { + "value" : 1.7214228922368E14 + }, + "ram-percentage" : { + "value" : 0.11671032934131736 + } + }, + { + "key" : 10000.0, + "doc_count" : 702, + "os-type" : { + "doc_count" : 116, + "total_ram" : { + "value" : 1.622423896064E12 + } + }, + "total_ram" : { + "value" : 9.015136354304E12 + }, + "ram-percentage" : { + "value" : 0.17996665078608862 + } + } + ] + } + } +} +``` + +RAM 百分比计算完成后会追加到每个桶的末尾。 + +`bucket_selector` 聚合是一种基于脚本的聚合,用于选择 `histogram`(或 `date_histogram`)聚合返回的桶。当你希望根据自己提供的条件从输出中排除某些桶时,可以使用它。 + +`bucket_selector` 聚合执行脚本,以决定某个桶是否保留在父多桶聚合中。 + +基本语法如下: + +```json +{ + "bucket_selector": { + "buckets_path": { + "my_var1": "the_sum", + "my_var2": "the_value_count" + }, + "script": "params.my_var1 / params.my_var2" + } +} +``` + +以下示例计算字节数总和,然后判断该总和是否大于 20,000。如果是,则该桶保留在桶列表中;否则,会从最终输出中删除。 + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "bytes_per_month": { + "date_histogram": { + "field": "@timestamp", + "calendar_interval": "month" + }, + "aggs": { + "total_bytes": { + "sum": { + "field": "bytes" + } + }, + "bytes_bucket_filter": { + "bucket_selector": { + "buckets_path": { + "totalBytes": "total_bytes" + }, + "script": "params.totalBytes > 20000" + } + } + } + } + } +} +``` + +#### 示例响应 {#example-response-5} + +```json +"aggregations" : { + "bytes_per_month" : { + "buckets" : [ + { + "key_as_string" : "2020-10-01T00:00:00.000Z", + "key" : 1601510400000, + "doc_count" : 1635, + "total_bytes" : { + "value" : 9400200.0 + } + }, + { + "key_as_string" : "2020-11-01T00:00:00.000Z", + "key" : 1604188800000, + "doc_count" : 6844, + "total_bytes" : { + "value" : 3.8880434E7 + } + }, + { + "key_as_string" : "2020-12-01T00:00:00.000Z", + "key" : 1606780800000, + "doc_count" : 5595, + "total_bytes" : { + "value" : 3.1445055E7 + } + } + ] + } + } +} +``` + +## bucket_sort {#bucketsort} + +`bucket_sort` 聚合是一种父聚合,用于对前一个聚合的桶进行排序。 + +你可以同时指定多个排序字段及其对应的排序顺序。此外,还可以根据每个桶的键、计数或其子聚合对桶进行排序。你也可以通过设置 `from` 和 `size` 参数来截断桶。 + +语法 + +```json +{ + "bucket_sort": { + "sort": [ + {"sort_field_1": {"order": "asc"}}, + {"sort_field_2": {"order": "desc"}}, + "sort_field_3" + ], + "from":1, + "size":3 + } +} +``` + +以下示例根据计算出的 `total_sum` 值对 `date_histogram` 聚合的桶进行排序。我们按降序对桶进行排序,使字节数最多的桶最先返回。 + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "sales_per_month": { + "date_histogram": { + "field": "@timestamp", + "calendar_interval": "month" + }, + "aggs": { + "total_bytes": { + "sum": { + "field": "bytes" + } + }, + "bytes_bucket_sort": { + "bucket_sort": { + "sort": [ + { "total_bytes": { "order": "desc" } } + ], + "size": 3 + } + } + } + } + } +} +``` + +#### 示例响应 {#example-response-6} + +```json +"aggregations" : { + "sales_per_month" : { + "buckets" : [ + { + "key_as_string" : "2020-11-01T00:00:00.000Z", + "key" : 1604188800000, + "doc_count" : 6844, + "total_bytes" : { + "value" : 3.8880434E7 + } + }, + { + "key_as_string" : "2020-12-01T00:00:00.000Z", + "key" : 1606780800000, + "doc_count" : 5595, + "total_bytes" : { + "value" : 3.1445055E7 + } + }, + { + "key_as_string" : "2020-10-01T00:00:00.000Z", + "key" : 1601510400000, + "doc_count" : 1635, + "total_bytes" : { + "value" : 9400200.0 + } + } + ] + } + } +} +``` + +你也可以使用此聚合在不排序的情况下截断结果桶。为此,只需使用 `from` 和/或 `size` 参数,而不使用 `sort`。 + +## cumulative_sum {#cumulativesum} + +`cumulative_sum` 聚合是一种父聚合,用于计算前一个聚合中每个桶的累积和。 + +累积和是给定序列的部分和所组成的序列。例如,序列 `{a,b,c,…}` 的累积和为 `a`、`a+b`、`a+b+c`,依此类推。你可以使用累积和来可视化某个字段随时间的变化率。 + +以下示例按月计算累积字节数: + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "sales_per_month": { + "date_histogram": { + "field": "@timestamp", + "calendar_interval": "month" + }, + "aggs": { + "no-of-bytes": { + "sum": { + "field": "bytes" + } + }, + "cumulative_bytes": { + "cumulative_sum": { + "buckets_path": "no-of-bytes" + } + } + } + } + } +} +``` + +#### 示例响应 {#example-response-7} + +```json +... +"aggregations" : { + "sales_per_month" : { + "buckets" : [ + { + "key_as_string" : "2020-10-01T00:00:00.000Z", + "key" : 1601510400000, + "doc_count" : 1635, + "no-of-bytes" : { + "value" : 9400200.0 + }, + "cumulative_bytes" : { + "value" : 9400200.0 + } + }, + { + "key_as_string" : "2020-11-01T00:00:00.000Z", + "key" : 1604188800000, + "doc_count" : 6844, + "no-of-bytes" : { + "value" : 3.8880434E7 + }, + "cumulative_bytes" : { + "value" : 4.8280634E7 + } + }, + { + "key_as_string" : "2020-12-01T00:00:00.000Z", + "key" : 1606780800000, + "doc_count" : 5595, + "no-of-bytes" : { + "value" : 3.1445055E7 + }, + "cumulative_bytes" : { + "value" : 7.9725689E7 + } + } + ] + } + } +} +``` + +## derivative + +`derivative` 聚合是一种父聚合,用于计算前一个聚合中每个桶的一阶导数和二阶导数。 + +在数学中,函数的导数衡量函数对变化的敏感程度。换句话说,导数评估的是某个函数相对于某个变量的变化率。要了解有关导数的更多信息,请参阅 [Wikipedia](https://en.wikipedia.org/wiki/Derivative)。 + +你可以使用导数来计算数值相对于之前时间段的变化率。 + +一阶导数表示某个指标是在增加还是减少,以及增加或减少了多少。 + +以下示例计算每月字节数总和的一阶导数。一阶导数是当月字节数与上月字节数之差: + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "sales_per_month": { + "date_histogram": { + "field": "@timestamp", + "calendar_interval": "month" + }, + "aggs": { + "number_of_bytes": { + "sum": { + "field": "bytes" + } + }, + "bytes_deriv": { + "derivative": { + "buckets_path": "number_of_bytes" + } + } + } + } + } +} +``` + +#### 示例响应 {#example-response-8} + +```json +... +"aggregations" : { + "sales_per_month" : { + "buckets" : [ + { + "key_as_string" : "2020-10-01T00:00:00.000Z", + "key" : 1601510400000, + "doc_count" : 1635, + "number_of_bytes" : { + "value" : 9400200.0 + } + }, + { + "key_as_string" : "2020-11-01T00:00:00.000Z", + "key" : 1604188800000, + "doc_count" : 6844, + "number_of_bytes" : { + "value" : 3.8880434E7 + }, + "bytes_deriv" : { + "value" : 2.9480234E7 + } + }, + { + "key_as_string" : "2020-12-01T00:00:00.000Z", + "key" : 1606780800000, + "doc_count" : 5595, + "number_of_bytes" : { + "value" : 3.1445055E7 + }, + "bytes_deriv" : { + "value" : -7435379.0 + } + } + ] + } + } +} +``` + +二阶导数是二重导数,即导数的导数。 +它表示某个量的变化率本身是如何变化的,即相邻桶的一阶导数之差。 + +要计算二阶导数,请将一个导数聚合串联到另一个导数聚合上: + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "sales_per_month": { + "date_histogram": { + "field": "@timestamp", + "calendar_interval": "month" + }, + "aggs": { + "number_of_bytes": { + "sum": { + "field": "bytes" + } + }, + "bytes_deriv": { + "derivative": { + "buckets_path": "number_of_bytes" + } + }, + "bytes_2nd_deriv": { + "derivative": { + "buckets_path": "bytes_deriv" + } + } + } + } + } +} +``` + +#### 示例响应 {#example-response-9} + +```json +... +"aggregations" : { + "sales_per_month" : { + "buckets" : [ + { + "key_as_string" : "2020-10-01T00:00:00.000Z", + "key" : 1601510400000, + "doc_count" : 1635, + "number_of_bytes" : { + "value" : 9400200.0 + } + }, + { + "key_as_string" : "2020-11-01T00:00:00.000Z", + "key" : 1604188800000, + "doc_count" : 6844, + "number_of_bytes" : { + "value" : 3.8880434E7 + }, + "bytes_deriv" : { + "value" : 2.9480234E7 + } + }, + { + "key_as_string" : "2020-12-01T00:00:00.000Z", + "key" : 1606780800000, + "doc_count" : 5595, + "number_of_bytes" : { + "value" : 3.1445055E7 + }, + "bytes_deriv" : { + "value" : -7435379.0 + }, + "bytes_2nd_deriv" : { + "value" : -3.6915613E7 + } + } + ] + } + } +} +``` + +第一个桶没有一阶导数,因为导数至少需要两个点才能进行比较。第一个和第二个桶没有二阶导数,因为二阶导数至少需要两个一阶导数数据点。 + +"2020-11-01" 桶的一阶导数为 2.9480234E7,"2020-12-01" 桶的一阶导数为 -7435379。因此,“2020-12-01” 桶的二阶导数为 -3.6915613E7(-7435379-2.9480234E7)。 + +理论上,你可以继续串联导数聚合来计算三阶、四阶乃至更高阶的导数。但对于大多数数据集来说,这样做几乎没有任何价值。 + +## moving_avg {#movingavg} + +`moving_avg` 聚合是一种父聚合,用于计算移动平均指标。 + +`moving_avg` 聚合求出数据集中不同窗口(子集)的一系列平均值。窗口大小表示每次迭代中窗口覆盖的数据点数量(由 `window` 属性指定,默认为 5)。每次迭代时,算法计算落入窗口的所有数据点的平均值,然后向前滑动:排除上一个窗口的第一个成员,并纳入下一个窗口的第一个成员。 + +例如,给定数据 `[1, 5, 8, 23, 34, 28, 7, 23, 20, 19]`,可以按如下方式计算窗口大小为 5 的简单移动平均值: + +``` +(1 + 5 + 8 + 23 + 34) / 5 = 14.2 +(5 + 8 + 23 + 34+ 28) / 5 = 19.6 +(8 + 23 + 34 + 28 + 7) / 5 = 20 +so on... +``` + +更多信息,请参阅 [Wikipedia](https://en.wikipedia.org/wiki/Moving_average)。 + +你可以使用 `moving_avg` 聚合来平滑时间序列数据中的短期波动,或突出其中的长期趋势或周期。 + +指定一个较小的窗口大小(例如 `window`: 10),使其紧密跟随数据,从而平滑小规模波动。 +或者,指定一个较大的窗口大小(例如 `window`: 100),使其明显滞后于实际数据,从而平滑所有较高频率的波动或随机噪声,让较低频率的趋势更加明显。 + +以下示例将 `moving_avg` 聚合嵌套到 `date_histogram` 聚合中: + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "my_date_histogram": { + "date_histogram": { + "field": "@timestamp", + "calendar_interval": "month" + }, + "aggs": { + "sum_of_bytes": { + "sum": { "field": "bytes" } + }, + "moving_avg_of_sum_of_bytes": { + "moving_avg": { "buckets_path": "sum_of_bytes" } + } + } + } + } +} +``` + +#### 示例响应 {#example-response-10} + +```json +... +"aggregations" : { + "my_date_histogram" : { + "buckets" : [ + { + "key_as_string" : "2020-10-01T00:00:00.000Z", + "key" : 1601510400000, + "doc_count" : 1635, + "sum_of_bytes" : { + "value" : 9400200.0 + } + }, + { + "key_as_string" : "2020-11-01T00:00:00.000Z", + "key" : 1604188800000, + "doc_count" : 6844, + "sum_of_bytes" : { + "value" : 3.8880434E7 + }, + "moving_avg_of_sum_of_bytes" : { + "value" : 9400200.0 + } + }, + { + "key_as_string" : "2020-12-01T00:00:00.000Z", + "key" : 1606780800000, + "doc_count" : 5595, + "sum_of_bytes" : { + "value" : 3.1445055E7 + }, + "moving_avg_of_sum_of_bytes" : { + "value" : 2.4140317E7 + } + } + ] + } + } +} +``` + +你还可以使用 `moving_avg` 聚合来预测未来的桶。 +要预测桶,请添加 `predict` 属性,并将其设置为你希望看到的预测数量。 + +以下示例在前面的查询中添加了五个预测值: + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "my_date_histogram": { + "date_histogram": { + "field": "@timestamp", + "calendar_interval": "month" + }, + "aggs": { + "sum_of_bytes": { + "sum": { + "field": "bytes" + } + }, + "moving_avg_of_sum_of_bytes": { + "moving_avg": { + "buckets_path": "sum_of_bytes", + "predict": 5 + } + } + } + } + } +} +``` + +#### 示例响应 {#example-response-11} + +```json +"aggregations" : { + "my_date_histogram" : { + "buckets" : [ + { + "key_as_string" : "2020-10-01T00:00:00.000Z", + "key" : 1601510400000, + "doc_count" : 1635, + "sum_of_bytes" : { + "value" : 9400200.0 + } + }, + { + "key_as_string" : "2020-11-01T00:00:00.000Z", + "key" : 1604188800000, + "doc_count" : 6844, + "sum_of_bytes" : { + "value" : 3.8880434E7 + }, + "moving_avg_of_sum_of_bytes" : { + "value" : 9400200.0 + } + }, + { + "key_as_string" : "2020-12-01T00:00:00.000Z", + "key" : 1606780800000, + "doc_count" : 5595, + "sum_of_bytes" : { + "value" : 3.1445055E7 + }, + "moving_avg_of_sum_of_bytes" : { + "value" : 2.4140317E7 + } + }, + { + "key_as_string" : "2021-01-01T00:00:00.000Z", + "key" : 1609459200000, + "doc_count" : 0, + "moving_avg_of_sum_of_bytes" : { + "value" : 2.6575229666666668E7 + } + }, + { + "key_as_string" : "2021-02-01T00:00:00.000Z", + "key" : 1612137600000, + "doc_count" : 0, + "moving_avg_of_sum_of_bytes" : { + "value" : 2.6575229666666668E7 + } + }, + { + "key_as_string" : "2021-03-01T00:00:00.000Z", + "key" : 1614556800000, + "doc_count" : 0, + "moving_avg_of_sum_of_bytes" : { + "value" : 2.6575229666666668E7 + } + }, + { + "key_as_string" : "2021-04-01T00:00:00.000Z", + "key" : 1617235200000, + "doc_count" : 0, + "moving_avg_of_sum_of_bytes" : { + "value" : 2.6575229666666668E7 + } + }, + { + "key_as_string" : "2021-05-01T00:00:00.000Z", + "key" : 1619827200000, + "doc_count" : 0, + "moving_avg_of_sum_of_bytes" : { + "value" : 2.6575229666666668E7 + } + } + ] + } + } +} +``` + +`moving_avg` 聚合支持五种模型:`simple`、`linear`、`exponentially weighted`、`holt-linear` 和 `holt-winters`。这些模型的区别在于对窗口中各值的加权方式。随着数据点变得“更旧”(即窗口逐渐滑离这些数据点),它们的权重可能会有所不同。你可以通过设置 `model` 属性来指定所需的模型。`model` 属性包含模型名称和 `settings` 对象,你可以使用该对象提供模型属性。有关这些模型的更多信息,请参阅 [Wikipedia](https://en.wikipedia.org/wiki/Moving_average)。 + +`simple` 模型首先计算窗口中所有数据点的总和,然后将该总和除以窗口大小。换句话说,`simple` 模型为数据集中的每个窗口计算一个简单的算术平均值。 + +以下示例使用窗口大小为 30 的 simple 模型: + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "my_date_histogram": { + "date_histogram": { + "field": "@timestamp", + "calendar_interval": "month" + }, + "aggs": { + "sum_of_bytes": { + "sum": { + "field": "bytes" + } + }, + "moving_avg_of_sum_of_bytes": { + "moving_avg": { + "buckets_path": "sum_of_bytes", + "window": 30, + "model": "simple" + } + } + } + } + } +} +``` + +#### 示例响应 {#example-response-12} + +```json +... +"aggregations" : { + "my_date_histogram" : { + "buckets" : [ + { + "key_as_string" : "2020-10-01T00:00:00.000Z", + "key" : 1601510400000, + "doc_count" : 1635, + "sum_of_bytes" : { + "value" : 9400200.0 + } + }, + { + "key_as_string" : "2020-11-01T00:00:00.000Z", + "key" : 1604188800000, + "doc_count" : 6844, + "sum_of_bytes" : { + "value" : 3.8880434E7 + }, + "moving_avg_of_sum_of_bytes" : { + "value" : 9400200.0 + } + }, + { + "key_as_string" : "2020-12-01T00:00:00.000Z", + "key" : 1606780800000, + "doc_count" : 5595, + "sum_of_bytes" : { + "value" : 3.1445055E7 + }, + "moving_avg_of_sum_of_bytes" : { + "value" : 2.4140317E7 + } + } + ] + } + } +} +``` + +以下示例使用 `holt` 模型。你可以通过 `alpha` 和 `beta` 设置来控制重要性衰减的速度。`alpha` 的默认值为 0.3,`beta` 的默认值为 0.1。你可以指定 0 到 1(含)之间的任意浮点值。 + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "my_date_histogram": { + "date_histogram": { + "field": "@timestamp", + "calendar_interval": "month" + }, + "aggs": { + "sum_of_bytes": { + "sum": { + "field": "bytes" + } + }, + "moving_avg_of_sum_of_bytes": { + "moving_avg": { + "buckets_path": "sum_of_bytes", + "model": "holt", + "settings": { + "alpha": 0.6, + "beta": 0.4 + } + } + } + } + } + } +} +``` + +#### 示例响应 {#example-response-13} + +```json +... +"aggregations" : { + "my_date_histogram" : { + "buckets" : [ + { + "key_as_string" : "2020-10-01T00:00:00.000Z", + "key" : 1601510400000, + "doc_count" : 1635, + "sum_of_bytes" : { + "value" : 9400200.0 + } + }, + { + "key_as_string" : "2020-11-01T00:00:00.000Z", + "key" : 1604188800000, + "doc_count" : 6844, + "sum_of_bytes" : { + "value" : 3.8880434E7 + }, + "moving_avg_of_sum_of_bytes" : { + "value" : 9400200.0 + } + }, + { + "key_as_string" : "2020-12-01T00:00:00.000Z", + "key" : 1606780800000, + "doc_count" : 5595, + "sum_of_bytes" : { + "value" : 3.1445055E7 + }, + "moving_avg_of_sum_of_bytes" : { + "value" : 2.70883404E7 + } + } + ] + } + } +} +``` + +## serial_diff {#serialdiff} + +`serial_diff` 聚合是一种父管道聚合,用于计算前一个聚合中相隔一定时间滞后的桶之间的一系列值差。 + +你可以使用 `serial_diff` 聚合来求出不同时间段之间的数据变化,而不是求出整个值。 + +通过 `lag` 参数(一个非零正整数值),你可以指定要从当前桶中减去哪个之前的桶。如果没有指定 `lag` 参数,OpenSearch 会将其设置为 1。 + +假设某个城市的人口随时间增长。如果你使用周期为一天的序列差分聚合,就可以看到每天的增长量。例如,你可以计算总价的每周平均变化量的一系列差值。 + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "my_date_histogram": { + "date_histogram": { + "field": "@timestamp", + "calendar_interval": "month" + }, + "aggs": { + "the_sum": { + "sum": { + "field": "bytes" + } + }, + "thirtieth_difference": { + "serial_diff": { + "buckets_path": "the_sum", + "lag" : 30 + } + } + } + } + } +} +``` + +#### 示例响应 {#example-response-14} + +```json +... +"aggregations" : { + "my_date_histogram" : { + "buckets" : [ + { + "key_as_string" : "2020-10-01T00:00:00.000Z", + "key" : 1601510400000, + "doc_count" : 1635, + "the_sum" : { + "value" : 9400200.0 + } + }, + { + "key_as_string" : "2020-11-01T00:00:00.000Z", + "key" : 1604188800000, + "doc_count" : 6844, + "the_sum" : { + "value" : 3.8880434E7 + } + }, + { + "key_as_string" : "2020-12-01T00:00:00.000Z", + "key" : 1606780800000, + "doc_count" : 5595, + "the_sum" : { + "value" : 3.1445055E7 + } + } + ] + } + } +} +``` diff --git a/i18n/zh/analyzers/index-analyzers.md b/i18n/zh/analyzers/index-analyzers.md new file mode 100644 index 00000000..8fde174d --- /dev/null +++ b/i18n/zh/analyzers/index-analyzers.md @@ -0,0 +1,62 @@ +--- +title: 索引分析器 +--- + +# 索引分析器 + +索引分析器(Index Analyzer)在索引时指定,用于在索引文档(Document)时分析 [text](/field-types/supported-field-types/text) 字段。 + +## 确定使用哪个索引分析器 + +为了确定在索引文档时对某个字段使用哪个分析器(Analyzer),OpenSearch 会按顺序检查以下参数: + +1. 字段的 `analyzer` 映射参数 +1. `analysis.analyzer.default` 索引设置 +1. `standard` 分析器(默认) + +::: warning 重要 +指定索引分析器时请注意,在大多数情况下,为索引中的每个 `text` 字段指定一个分析器效果最好。使用同一个分析器分析 text 字段(在索引时)和查询字符串(在查询时),可以确保搜索使用的词项与索引中存储的词项相同。 +::: + +关于如何验证哪个分析器与哪个字段关联,请参阅[验证分析器设置](/analyzers/#verifying-analyzer-settings)。 + +## 为字段指定索引分析器 + +创建索引映射(Mapping)时,你可以为每个 [text](/field-types/supported-field-types/text) 字段提供 `analyzer` 参数。例如,以下请求为 `text_entry` 字段指定了 `simple` 分析器: + +```json +PUT testindex +{ + "mappings": { + "properties": { + "text_entry": { + "type": "text", + "analyzer": "simple" + } + } + } +} +``` + +## 为索引指定默认索引分析器 + +如果你想对索引中的所有 text 字段使用同一个分析器,可以在 `analysis.analyzer.default` 设置中指定,如下所示: + +```json +PUT testindex +{ + "settings": { + "analysis": { + "analyzer": { + "default": { + "type": "simple" + } + } + } + } +} +``` + +::: info 注意 +如果没有指定默认分析器,则使用 `standard` 分析器。 +::: diff --git a/i18n/zh/analyzers/index.md b/i18n/zh/analyzers/index.md new file mode 100644 index 00000000..852ce503 --- /dev/null +++ b/i18n/zh/analyzers/index.md @@ -0,0 +1,165 @@ +--- +title: 文本分析 +--- + +# 文本分析 + +使用全文搜索来搜索文档时,你希望获得所有相关的结果。如果你在查找 "walk",那么你会对包含该单词任何形式的结果感兴趣,例如 "Walk"、"walked" 或 "walking"。为了支持全文搜索,OpenSearch 使用了文本分析。 + +文本分析的目标是将源文档中非结构化的自由文本内容拆分为一系列词项,然后将这些词项存储在倒排索引中。之后,当对用户的查询应用类似的文本分析时,得到的词项序列就可以用来匹配相关的源文档。 + +从技术角度来看,文本分析过程由几个步骤组成,其中一些步骤是可选的: + +1. 在将自由文本内容拆分为单个单词之前,在字符层面对文本进行优化可能会有所帮助。这个可选步骤的主要目的是帮助分词器(分析过程中的下一个阶段)生成更好的词元。这可能包括移除标记标签(例如 HTML),或处理特定的字符模式(例如将 🙂 表情符号替换为文本 `:slightly_smiling_face:`)。 + +2. 下一步是将自由文本拆分为单个单词,即*词元(Token)*。这一步由*分词器(Tokenizer)* 完成。例如,经过分词后,句子 `Actions speak louder than words` 会被拆分为词元 `Actions`、`speak`、`louder`、`than` 和 `words`。 + +3. 最后一步是通过应用一系列词元过滤器(Token Filter)来处理各个词元。其目的是将每个词元转换为可预测的形式,并直接存储在索引中,例如将词元转换为小写或进行词干提取(将单词还原为词根)。例如,词元 `Actions` 变为 `action`,`louder` 变为 `loud`,`words` 变为 `word`。 + +::: info 注意 +虽然 ***token***(词元)和 ***term***(词项)这两个术语听起来相似,有时也会互换使用,但了解两者之间的区别会很有帮助。在 Apache Lucene 中,二者各自扮演不同的角色。***token*** 是在文本分析过程中由分词器创建的,在经过词元过滤器链时通常还会经历多次额外的修改。每个词元都关联着一些元数据,这些元数据可以在文本分析过程中进一步使用。***term*** 是直接存储在倒排索引中的数据值,关联的元数据要少得多。在搜索过程中,匹配是在词项级别进行的。 +::: + +## 分析器 + +在 OpenSearch 中,涵盖文本分析的抽象称为*分析器(Analyzer)*。每个分析器都包含以下按顺序应用的组件: + +1. **字符过滤器(Character Filter)**:首先,字符过滤器以字符流的形式接收原始文本,并在文本中添加、删除或修改字符。例如,字符过滤器可以从字符串中去除 HTML 字符,使文本 `

Actions speak louder than words

` 变为 `\nActions speak louder than words\n`。字符过滤器的输出是字符流。 + +1. **分词器**:接下来,分词器接收经过字符过滤器处理的字符流,并将文本拆分为单独的*词元*(通常是单词)。例如,分词器可以按空白字符拆分文本,使前面的文本变为 [`Actions`, `speak`, `louder`, `than`, `words`]。分词器还会维护关于词元的元数据,例如词元在文本中的起始和结束位置。分词器的输出是词元流。 + +1. **词元过滤器**:最后,词元过滤器接收来自分词器的词元流,并添加、删除或修改词元。例如,词元过滤器可以将词元转换为小写,使 `Actions` 变为 `action`;可以删除 `than` 这样的停用词;也可以为单词 `speak` 添加 `talk` 这样的同义词。 + +::: info 注意 +一个分析器必须恰好包含一个分词器,并且可以包含零个或多个字符过滤器,以及零个或多个词元过滤器。 +::: + +还有一种特殊类型的分析器,称为 ***规范化器(Normalizer)***。规范化器与分析器类似,不同之处在于它不包含分词器,并且只能包含特定类型的字符过滤器和词元过滤器。这些过滤器只能执行字符级操作,例如字符替换或模式替换,而不能对整个词元进行操作。这意味着不支持将词元替换为同义词,也不支持词干提取。更多详细信息,请参阅[规范化器](/analyzers/normalizers)。 + +## 内置分析器 + +下表列出了 OpenSearch 提供的内置分析器。表格的最后一列是将该分析器应用于字符串 `It’s fun to contribute a brand-new PR or 2 to OpenSearch!` 的结果。 + +分析器 | 执行的分析 | 分析器输出 +:--- | :--- | :--- +**Standard**(默认) | - 在单词边界处将字符串解析为词元
- 移除大部分标点符号
- 将词元转换为小写 | [`it’s`, `fun`, `to`, `contribute`, `a`,`brand`, `new`, `pr`, `or`, `2`, `to`, `opensearch`] +**Simple** | - 在任何非字母字符处将字符串解析为词元
- 移除非字母字符
- 将词元转换为小写 | [`it`, `s`, `fun`, `to`, `contribute`, `a`,`brand`, `new`, `pr`, `or`, `to`, `opensearch`] +**Whitespace** | - 在空白字符处将字符串解析为词元 | [`It’s`, `fun`, `to`, `contribute`, `a`,`brand-new`, `PR`, `or`, `2`, `to`, `OpenSearch!`] +**Stop** | - 在任何非字母字符处将字符串解析为词元
- 移除非字母字符
- 移除停用词
- 将词元转换为小写 | [`s`, `fun`, `contribute`, `brand`, `new`, `pr`, `opensearch`] +**Keyword**(不执行任何操作) | - 原样输出整个字符串 | [`It’s fun to contribute a brand-new PR or 2 to OpenSearch!`] +**Pattern** | - 使用正则表达式将字符串解析为词元
- 支持将字符串转换为小写
- 支持移除停用词 | [`it`, `s`, `fun`, `to`, `contribute`, `a`,`brand`, `new`, `pr`, `or`, `2`, `to`, `opensearch`] +[**Language**](/analyzers/language-analyzers) | 执行针对特定语言(例如 `english`)的分析。 | [`fun`, `contribut`, `brand`, `new`, `pr`, `2`, `opensearch`] +**Fingerprint** | - 在任何非字母字符处解析字符串
- 通过将字符转换为 ASCII 来规范化字符
- 将词元转换为小写
- 对词元进行排序、去重,并连接成单个词元
- 支持移除停用词 | [`2 a brand contribute fun it's new opensearch or pr to`]
注意,撇号被转换成了对应的 ASCII 字符。 + +## 自定义分析器 + +如有需要,你可以组合分词器、词元过滤器和字符过滤器来创建自定义分析器。 + +## 索引时和查询时的文本分析 + +OpenSearch 在你索引文档以及发送搜索请求时,都会对 text 字段执行文本分析。根据文本分析发生的时间,所用的分析器分为以下两类: + +- *索引分析器* 在索引时执行分析:当你索引一个 [text](/field-types/supported-field-types/text) 字段时,OpenSearch 会在索引之前对其进行分析。有关指定索引分析器的方式的更多信息,请参阅[索引分析器](/analyzers/index-analyzers)。 + +- *搜索分析器* 在查询时执行分析:当你对 text 字段运行全文查询(Full-text Query)时,OpenSearch 会分析查询字符串。有关指定搜索分析器的方式的更多信息,请参阅[搜索分析器](/analyzers/search-analyzers)。 + +::: tip 提示 +在大多数情况下,你应该在索引和搜索时使用相同的分析器,因为这样 text 字段和查询字符串会以相同的方式进行分析,生成的词元也会如预期那样匹配。 +::: + +### 示例 + +当你索引一个文档,其 text 字段包含文本 `Actions speak louder than words` 时,OpenSearch 会分析该文本并生成以下词元列表: + +Text 字段词元 = [`action`, `speak`, `loud`, `than`, `word`] + +当你搜索与查询 `speaking loudly` 匹配的文档时,OpenSearch 会分析查询字符串并生成以下词元列表: + +查询字符串词元 = [`speak`, `loud`] + +然后,OpenSearch 将查询字符串中的每个词元与 text 字段的词元列表进行比较,发现两个列表都包含词元 `speak` 和 `loud`,因此 OpenSearch 会将该文档作为匹配查询的搜索结果之一返回。 + +## 测试分析器 + +要测试内置分析器,并查看文档被索引时它生成的词元列表,可以使用 [Analyze API](/api-reference/analyze-apis#apply-a-built-in-analyzer)。 + +在请求中指定分析器和要分析的文本: + +```json +GET /_analyze +{ + "analyzer" : "standard", + "text" : "Let’s contribute to OpenSearch!" +} +``` + +下图显示了该查询字符串。 + +![带索引位置的查询字符串](/images/string-indices.png) + +响应中包含每个词元及其起始和结束偏移量,分别对应原始字符串中的起始索引位置(包含)和结束索引位置(不包含): + +```json +{ + "tokens": [ + { + "token": "let’s", + "start_offset": 0, + "end_offset": 5, + "type": "", + "position": 0 + }, + { + "token": "contribute", + "start_offset": 6, + "end_offset": 16, + "type": "", + "position": 1 + }, + { + "token": "to", + "start_offset": 17, + "end_offset": 19, + "type": "", + "position": 2 + }, + { + "token": "opensearch", + "start_offset": 20, + "end_offset": 30, + "type": "", + "position": 3 + } + ] +} +``` + +## 验证分析器设置 + +要验证哪个分析器与哪个字段关联,可以使用获取映射(get mapping)API 操作: + +```json +GET /testindex/_mapping +``` + +响应提供了每个字段的分析器信息: + +```json +{ + "testindex": { + "mappings": { + "properties": { + "text_entry": { + "type": "text", + "analyzer": "simple", + "search_analyzer": "whitespace" + } + } + } + } +} +``` + +## 后续步骤 + +- 详细了解如何指定[索引分析器](/analyzers/index-analyzers)和[搜索分析器](/analyzers/search-analyzers)。 diff --git a/i18n/zh/analyzers/language-analyzers.md b/i18n/zh/analyzers/language-analyzers.md new file mode 100644 index 00000000..67c12eb6 --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers.md @@ -0,0 +1,39 @@ +--- +title: 语言分析器 +--- + +# 语言分析器 + +OpenSearch 的 `analyzer` 选项支持以下语言值: +`arabic`、`armenian`、`basque`、`bengali`、`brazilian`、`bulgarian`、`catalan`、`czech`、`danish`、`dutch`、`english`、`estonian`、`finnish`、`french`、`galician`、`german`、`greek`、`hindi`、`hungarian`、`indonesian`、`irish`、`italian`、`latvian`、`lithuanian`、`norwegian`、`persian`、`portuguese`、`romanian`、`russian`、`sorani`、`spanish`、`swedish`、`turkish` 和 `thai`。 + +要在映射索引时使用该分析器,请在查询中指定该值。例如,要使用法语分析器映射索引,请为 analyzer 字段指定 `french` 值: + +```json + "analyzer": "french" +``` + +#### 示例请求 + +以下查询为索引 `my-index` 指定了 `french` 语言分析器: + +```json +PUT my-index +{ + "mappings": { + "properties": { + "text": { + "type": "text", + "fields": { + "french": { + "type": "text", + "analyzer": "french" + } + } + } + } + } +} +``` + + diff --git a/i18n/zh/analyzers/normalizers.md b/i18n/zh/analyzers/normalizers.md new file mode 100644 index 00000000..e5b8be2e --- /dev/null +++ b/i18n/zh/analyzers/normalizers.md @@ -0,0 +1,106 @@ +--- +title: 规范化器 +--- + +# 规范化器 + +*规范化器(Normalizer)* 的作用与分析器类似,但只输出单个词元(Token)。它不包含分词器(Tokenizer),并且只能包含特定类型的字符过滤器(Character Filter)和词元过滤器(Token Filter)。这些过滤器只能执行字符级操作,例如字符替换或模式替换,而不能对整个词元进行操作。这意味着不支持将词元替换为同义词,也不支持词干提取。 + +规范化器在关键字搜索(即基于词项的查询)中很有用,因为它允许你对任意输入运行词元过滤器和字符过滤器。例如,它可以让传入的查询 `Naïve` 与索引词项 `naive` 相匹配。 + +请看下面的示例。 + +创建一个带有自定义规范化器的新索引: +```json +PUT /sample-index +{ + "settings": { + "analysis": { + "normalizer": { + "normalized_keyword": { + "type": "custom", + "char_filter": [], + "filter": [ "asciifolding", "lowercase" ] + } + } + } + }, + "mappings": { + "properties": { + "approach": { + "type": "keyword", + "normalizer": "normalized_keyword" + } + } + } +} +``` + +索引一个文档: +```json +POST /sample-index/_doc/ +{ + "approach": "naive" +} +``` + +以下查询会匹配该文档,这符合预期: +```json +GET /sample-index/_search +{ + "query": { + "term": { + "approach": "naive" + } + } +} +``` + +但下面这个查询同样会匹配该文档: +```json +GET /sample-index/_search +{ + "query": { + "term": { + "approach": "Naïve" + } + } +} +``` + +要理解其中的原因,请看规范化器的作用效果: +```json +GET /sample-index/_analyze +{ + "normalizer" : "normalized_keyword", + "text" : "Naïve" +} +``` + +在内部,规范化器只接受 `NormalizingTokenFilterFactory` 或 `NormalizingCharFilterFactory` 的实例作为过滤器。以下列出了 OpenSearch 核心仓库中各模块和插件所提供的兼容过滤器。 + +### `common-analysis` 模块 + +此模块无需安装,默认可用。 + +字符过滤器:`pattern_replace`、`mapping` + +词元过滤器:`arabic_normalization`、`asciifolding`、`bengali_normalization`、`cjk_width`、`decimal_digit`、`elision`、`german_normalization`、`hindi_normalization`、`indic_normalization`、`lowercase`、`persian_normalization`、`scandinavian_folding`、`scandinavian_normalization`、`serbian_normalization`、`sorani_normalization`、`trim`、`uppercase` + +### `analysis-icu` 插件 + +字符过滤器:`icu_normalizer` + +词元过滤器:`icu_normalizer`、`icu_folding`、`icu_transform` + +### `analysis-kuromoji` 插件 + +字符过滤器:`normalize_kanji`、`normalize_kana` + +### `analysis-nori` 插件 + +字符过滤器:`normalize_kanji`、`normalize_kana` + +::: info 注意 +这些过滤器列表仅包含 OpenSearch 核心仓库中[附加插件](/install-and-configure/plugins#additional-plugins)所提供的分析组件。 +::: diff --git a/i18n/zh/analyzers/search-analyzers.md b/i18n/zh/analyzers/search-analyzers.md new file mode 100644 index 00000000..1aac315d --- /dev/null +++ b/i18n/zh/analyzers/search-analyzers.md @@ -0,0 +1,89 @@ +--- +title: 搜索分析器 +--- + +# 搜索分析器 + +搜索分析器(Search Analyzer)在查询时指定,用于在对 [text](/field-types/supported-field-types/text) 字段运行全文查询(Full-text Query)时分析查询字符串。 + +## 确定使用哪个搜索分析器 + +为了确定在查询时对查询字符串使用哪个分析器(Analyzer),OpenSearch 会按顺序检查以下参数: + +1. 查询的 `analyzer` 参数 +1. 字段的 `search_analyzer` 映射参数 +1. `analysis.analyzer.default_search` 索引设置 +1. 字段的 `analyzer` 映射参数 +1. `standard` 分析器(默认) + +::: danger 警告 +在大多数情况下,没有必要指定与索引分析器不同的搜索分析器,这样做可能会降低搜索结果的相关性,或导致意外的搜索结果。 +::: + +关于如何验证哪个分析器与哪个字段关联,请参阅[验证分析器设置](/analyzers/#verifying-analyzer-settings)。 + +## 为查询字符串指定搜索分析器 + +在 `analyzer` 字段中指定查询时要使用的分析器名称: + +```json +GET shakespeare/_search +{ + "query": { + "match": { + "text_entry": { + "query": "speak the truth", + "analyzer": "english" + } + } + } +} +``` + +[内置分析器](/analyzers/#built-in-analyzers)的有效值为 `standard`、`simple`、`whitespace`、`stop`、`keyword`、`pattern`、`fingerprint`,或任何受支持的[语言分析器](/analyzers/language-analyzers)。 + +## 为字段指定搜索分析器 + +创建索引映射(Mapping)时,你可以为每个 [text](/field-types/supported-field-types/text) 字段提供 `search_analyzer` 参数。提供 `search_analyzer` 时,还必须提供 `analyzer` 参数,用于指定索引时使用的[索引分析器](/analyzers/index-analyzers)。 + +例如,以下请求为 `text_entry` 字段指定 `simple` 分析器作为索引分析器,`whitespace` 分析器作为搜索分析器: + +```json +PUT testindex +{ + "mappings": { + "properties": { + "text_entry": { + "type": "text", + "analyzer": "simple", + "search_analyzer": "whitespace" + } + } + } +} +``` + +## 为索引指定默认搜索分析器 + +如果你想在搜索时使用同一个分析器分析所有查询字符串,可以在 `analysis.analyzer.default_search` 设置中指定搜索分析器。提供 `analysis.analyzer.default_search` 时,还必须提供 `analysis.analyzer.default` 参数,用于指定索引时使用的[索引分析器](/analyzers/index-analyzers)。 + +例如,以下请求为 `testindex` 索引指定 `simple` 分析器作为索引分析器,`whitespace` 分析器作为搜索分析器: + +```json +PUT testindex +{ + "settings": { + "analysis": { + "analyzer": { + "default": { + "type": "simple" + }, + "default_search": { + "type": "whitespace" + } + } + } + } +} + +``` diff --git a/i18n/zh/analyzers/token-filters/delimited-term-frequency.md b/i18n/zh/analyzers/token-filters/delimited-term-frequency.md new file mode 100644 index 00000000..827e95c5 --- /dev/null +++ b/i18n/zh/analyzers/token-filters/delimited-term-frequency.md @@ -0,0 +1,266 @@ +--- +title: 分隔词频 +--- + +# 分隔词频词元过滤器 + +`delimited_term_freq` 词元过滤器(Token Filter)根据提供的分隔符,将词元流拆分为词元及其对应的词频。分隔符之前的所有字符构成词元,分隔符之后的整数为词频。例如,如果分隔符为 `|`,那么对于字符串 `foo|5`,`foo` 是词元,`5` 是它的词频。如果没有分隔符,该词元过滤器不会修改词频。 + +你可以使用预配置的 `delimited_term_freq` 词元过滤器,也可以创建自定义的过滤器。 + +## 预配置的 `delimited_term_freq` 词元过滤器 + +预配置的 `delimited_term_freq` 词元过滤器使用默认分隔符 `|`。要使用预配置的词元过滤器分析文本,请向 `_analyze` 端点发送以下请求: + +```json +POST /_analyze +{ + "text": "foo|100", + "tokenizer": "keyword", + "filter": ["delimited_term_freq"], + "attributes": ["termFrequency"], + "explain": true +} +``` + +`attributes` 数组表示你希望过滤 `explain` 参数的输出,只返回 `termFrequency`。响应中既包含原始词元,也包含该词元过滤器解析后的输出(其中包括词频): + +```json +{ + "detail": { + "custom_analyzer": true, + "charfilters": [], + "tokenizer": { + "name": "keyword", + "tokens": [ + { + "token": "foo|100", + "start_offset": 0, + "end_offset": 7, + "type": "word", + "position": 0, + "termFrequency": 1 + } + ] + }, + "tokenfilters": [ + { + "name": "delimited_term_freq", + "tokens": [ + { + "token": "foo", + "start_offset": 0, + "end_offset": 7, + "type": "word", + "position": 0, + "termFrequency": 100 + } + ] + } + ] + } +} +``` + +## 自定义 `delimited_term_freq` 词元过滤器 + +要配置自定义 `delimited_term_freq` 词元过滤器,首先在映射请求中指定分隔符,本例中为 `^`: + +```json +PUT /testindex +{ + "settings": { + "analysis": { + "filter": { + "my_delimited_term_freq": { + "type": "delimited_term_freq", + "delimiter": "^" + } + } + } + } +} +``` + +然后使用你创建的自定义词元过滤器分析文本: + +```json +POST /testindex/_analyze +{ + "text": "foo^3", + "tokenizer": "keyword", + "filter": ["my_delimited_term_freq"], + "attributes": ["termFrequency"], + "explain": true +} +``` + +响应中既包含原始词元,也包含解析后带有词频的版本: + +```json +{ + "detail": { + "custom_analyzer": true, + "charfilters": [], + "tokenizer": { + "name": "keyword", + "tokens": [ + { + "token": "foo|100", + "start_offset": 0, + "end_offset": 7, + "type": "word", + "position": 0, + "termFrequency": 1 + } + ] + }, + "tokenfilters": [ + { + "name": "delimited_term_freq", + "tokens": [ + { + "token": "foo", + "start_offset": 0, + "end_offset": 7, + "type": "word", + "position": 0, + "termFrequency": 100 + } + ] + } + ] + } +} +``` + +## 将 `delimited_token_filter` 与脚本结合使用 + +你可以编写 Painless 脚本,为结果中的文档计算自定义评分。 + +首先,创建一个索引并提供以下映射和设置: + +```json +PUT /test +{ + "settings": { + "number_of_shards": 1, + "analysis": { + "tokenizer": { + "keyword_tokenizer": { + "type": "keyword" + } + }, + "filter": { + "my_delimited_term_freq": { + "type": "delimited_term_freq", + "delimiter": "^" + } + }, + "analyzer": { + "custom_delimited_analyzer": { + "tokenizer": "keyword_tokenizer", + "filter": ["my_delimited_term_freq"] + } + } + } + }, + "mappings": { + "properties": { + "f1": { + "type": "keyword" + }, + "f2": { + "type": "text", + "analyzer": "custom_delimited_analyzer", + "index_options": "freqs" + } + } + } +} +``` + +`test` 索引使用了一个 keyword 分词器、一个分隔词频词元过滤器(分隔符为 `^`),以及一个包含 keyword 分词器和分隔词频词元过滤器的自定义分析器。映射指定字段 `f1` 为 keyword 字段,字段 `f2` 为 text 字段。字段 `f2` 使用设置中定义的自定义分析器进行文本分析。此外,指定 `index_options` 会通知 OpenSearch 将词频添加到倒排索引中。你将使用这些词频为包含重复词项的文档赋予更高的评分。 + +接下来,使用批量上传索引两个文档: + +```json +POST /_bulk?refresh=true +{"index": {"_index": "test", "_id": "doc1"}} +{"f1": "v0|100", "f2": "v1^30"} +{"index": {"_index": "test", "_id": "doc2"}} +{"f2": "v2|100"} +``` + +以下查询会搜索索引中的所有文档,并将字段 `f2` 中词项 `v1` 的词频作为文档评分: + +```json +GET /test/_search +{ + "query": { + "function_score": { + "query": { + "match_all": {} + }, + "script_score": { + "script": { + "source": "termFreq(params.field, params.term)", + "params": { + "field": "f2", + "term": "v1" + } + } + } + } + } +} +``` + +在响应中,文档 1 的评分为 30,因为字段 `f2` 中词项 `v1` 的词频为 30。文档 2 的评分为 0,因为词项 `v1` 没有出现在 `f2` 中: + +```json +{ + "took": 4, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 30, + "hits": [ + { + "_index": "test", + "_id": "doc1", + "_score": 30, + "_source": { + "f1": "v0|100", + "f2": "v1^30" + } + }, + { + "_index": "test", + "_id": "doc2", + "_score": 0, + "_source": { + "f2": "v2|100" + } + } + ] + } +} +``` + +## 参数 + +下表列出了 `delimited_term_freq` 支持的所有参数。 + +参数 | 必需/可选 | 描述 +:--- | :--- | :--- +`delimiter` | 可选 | 用于将词元与词频分隔开的分隔符。必须是单个非空字符。默认值为 `|`。 diff --git a/i18n/zh/analyzers/token-filters/index.md b/i18n/zh/analyzers/token-filters/index.md new file mode 100644 index 00000000..5f906c68 --- /dev/null +++ b/i18n/zh/analyzers/token-filters/index.md @@ -0,0 +1,60 @@ +--- +title: 词元过滤器 +--- + +# 词元过滤器 + +词元过滤器(Token Filter)接收来自分词器(Tokenizer)的词元(Token)流,并添加、删除或修改词元。例如,词元过滤器可以将词元转换为小写,使 `Actions` 变为 `action`;可以删除 `than` 这样的停用词;也可以为单词 `speak` 添加 `talk` 这样的同义词。 + +下表列出了 OpenSearch 支持的所有词元过滤器。 + +词元过滤器 | 底层 Lucene 词元过滤器| 描述 +`apostrophe` | [ApostropheFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/tr/ApostropheFilter.html) | 对于每个包含撇号的词元,`apostrophe` 词元过滤器会删除撇号本身及其后的所有字符。 +`asciifolding` | [ASCIIFoldingFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/miscellaneous/ASCIIFoldingFilter.html) | 转换字母、数字和符号字符。 +`cjk_bigram` | [CJKBigramFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/cjk/CJKBigramFilter.html) | 将中文、日文和韩文(CJK)词元组成二元组(bigram)。 +`cjk_width` | [CJKWidthFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/cjk/CJKWidthFilter.html) | 按以下规则规范化中文、日文和韩文(CJK)词元:
- 将全角 ASCII 字符变体折叠为等效的基本拉丁字符。
- 将半角片假名字符变体折叠为等效的假名字符。 +`classic` | [ClassicFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/standard/ClassicFilter.html) | 对 classic 分词器生成的词元执行可选的后处理。删除所有格(`'s`),并删除首字母缩写词中的 `.`。 +`common_grams` | [CommonGramsFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/commongrams/CommonGramsFilter.html) | 为一组高频出现的词项生成二元组。输出同时包含单个词项和二元组。 +`conditional` | [ConditionalTokenFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/miscellaneous/ConditionalTokenFilter.html) | 对符合脚本中所提供条件的词元,应用一个有序的词元过滤器列表。 +`decimal_digit` | [DecimalDigitFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/core/DecimalDigitFilter.html) | 将 Unicode 十进制数字通用类别中的所有数字转换为基本拉丁数字(0--9)。 +`delimited_payload` | [DelimitedPayloadTokenFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/payloads/DelimitedPayloadTokenFilter.html) | 根据提供的分隔符,将词元流拆分为词元及其对应的载荷(payload)。分隔符之前的所有字符构成词元,分隔符之后的所有字符构成载荷。例如,如果分隔符为 `|`,那么对于字符串 `foo|bar`,`foo` 是词元,`bar` 是载荷。 +[`delimited_term_freq`](/analyzers/token-filters/delimited-term-frequency) | [DelimitedTermFrequencyTokenFilter](https://lucene.apache.org/core/9_7_0/analysis/common/org/apache/lucene/analysis/miscellaneous/DelimitedTermFrequencyTokenFilter.html) | 根据提供的分隔符,将词元流拆分为词元及其对应的词频。分隔符之前的所有字符构成词元,分隔符之后的整数为词频。例如,如果分隔符为 `|`,那么对于字符串 `foo|5`,`foo` 是词元,`5` 是词频。 +`dictionary_decompounder` | [DictionaryCompoundWordTokenFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/compound/DictionaryCompoundWordTokenFilter.html) | 分解许多日耳曼语系语言中的复合词。 +`edge_ngram` | [EdgeNGramTokenFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/ngram/EdgeNGramTokenFilter.html) | 将给定词元切分为长度介于 `min_gram` 和 `max_gram` 之间的 edge n-gram(从词元开头开始的 n-gram)。可以选择保留原始词元。 +`elision` | [ElisionFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/util/ElisionFilter.html) | 从词元开头删除指定的[省略形式](https://en.wikipedia.org/wiki/Elision)。例如,将 `l'avion`(这架飞机)变为 `avion`(飞机)。 +`fingerprint` | [FingerprintFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/miscellaneous/FingerprintFilter.html) | 对词元列表进行排序和去重,并将词元连接成单个词元。 +`flatten_graph` | [FlattenGraphFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/core/FlattenGraphFilter.html) | 将由图词元过滤器(例如 `synonym_graph` 或 `word_delimiter_graph`)生成的词元图展平,使其适合用于索引。 +`hunspell` | [HunspellStemFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/hunspell/HunspellStemFilter.html) | 使用 [Hunspell](https://en.wikipedia.org/wiki/Hunspell) 规则对词元进行词干提取。由于 Hunspell 支持一个单词有多个词干,此过滤器对每个输入词元可能输出多个词元。需要配置一个或多个特定语言的 Hunspell 词典。 +`hyphenation_decompounder` | [HyphenationCompoundWordTokenFilter](https://lucene.apache.org/core/9_8_0/analysis/common/org/apache/lucene/analysis/compound/HyphenationCompoundWordTokenFilter.html) | 使用基于 XML 的连字符模式在复合词中查找可能的子词,并根据指定的单词列表检查这些子词。输出的词元只包含在单词列表中找到的子词。 +`keep_types` | [TypeTokenFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/core/TypeTokenFilter.html) | 保留或删除特定类型的词元。 +`keep_word` | [KeepWordFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/miscellaneous/KeepWordFilter.html) | 根据指定的单词列表检查词元,只保留列表中的词元。 +`keyword_marker` | [KeywordMarkerFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/miscellaneous/KeywordMarkerFilter.html) | 将指定的词元标记为关键字,防止对其进行词干提取。 +`keyword_repeat` | [KeywordRepeatFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/miscellaneous/KeywordRepeatFilter.html) | 将每个输入词元输出两次:一次作为关键字,一次作为非关键字。 +`kstem` | [KStemFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/en/KStemFilter.html) | 为英语提供基于 kstem 的词干提取。将算法词干提取与内置词典相结合。 +`length` | [LengthFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/miscellaneous/LengthFilter.html) | 删除长度短于或长于 `min` 和 `max` 所指定长度范围的词元。 +`limit` | [LimitTokenCountFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/miscellaneous/LimitTokenCountFilter.html) | 限制输出词元的数量。常见用例是根据词元数量限制文档字段值的大小。 +`lowercase` | [LowerCaseFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/core/LowerCaseFilter.html) | 将词元转换为小写。默认的 [LowerCaseFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/core/LowerCaseFilter.html) 适用于英语。你可以将 `language` 参数设置为 `greek`(使用 [GreekLowerCaseFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/el/GreekLowerCaseFilter.html))、`irish`(使用 [IrishLowerCaseFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/ga/IrishLowerCaseFilter.html))或 `turkish`(使用 [TurkishLowerCaseFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/tr/TurkishLowerCaseFilter.html))。 +`min_hash` | [MinHashFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/minhash/MinHashFilter.html) | 使用 [MinHash 技术](https://en.wikipedia.org/wiki/MinHash)估算文档相似度。按顺序对词元流执行以下操作:
1. 对流中的每个词元计算哈希值。
2. 将哈希值分配到桶(Bucket)中,每个桶只保留最小的哈希值。
3. 将每个桶中最小的哈希值作为词元流输出。 +`multiplexer` | N/A | 在同一位置输出多个词元。让每个词元分别经过每个指定的过滤器列表,并将结果作为单独的词元输出。 +`ngram` | [NGramTokenFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/ngram/NGramTokenFilter.html) | 将给定词元切分为长度介于 `min_gram` 和 `max_gram` 之间的 n-gram。 +规范化 | `arabic_normalization`: [ArabicNormalizer](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/ar/ArabicNormalizer.html)
`german_normalization`: [GermanNormalizationFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/de/GermanNormalizationFilter.html)
`hindi_normalization`: [HindiNormalizer](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/hi/HindiNormalizer.html)
`indic_normalization`: [IndicNormalizer](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/in/IndicNormalizer.html)
`sorani_normalization`: [SoraniNormalizer](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/ckb/SoraniNormalizer.html)
`persian_normalization`: [PersianNormalizer](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/fa/PersianNormalizer.html)
`scandinavian_normalization` : [ScandinavianNormalizationFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/miscellaneous/ScandinavianNormalizationFilter.html)
`scandinavian_folding`: [ScandinavianFoldingFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/miscellaneous/ScandinavianFoldingFilter.html)
`serbian_normalization`: [SerbianNormalizationFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/sr/SerbianNormalizationFilter.html) | 规范化所列语言之一的字符。 +`pattern_capture` | N/A | 为所提供正则表达式中的每个捕获组生成一个词元。使用 [Java 正则表达式语法](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html)。 +`pattern_replace` | N/A | 匹配所提供正则表达式中的模式,并替换匹配的子字符串。使用 [Java 正则表达式语法](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html)。 +`phonetic` | N/A | 使用语音编码器为词元流中的每个词元输出一个 metaphone 词元。需要安装 `analysis-phonetic` 插件。 +`porter_stem` | [PorterStemFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/en/PorterStemFilter.html) | 使用 [Porter 词干提取算法](https://tartarus.org/martin/PorterStemmer/)对英语执行算法词干提取。 +`predicate_token_filter` | N/A | 删除与指定谓词脚本不匹配的词元。仅支持内联 Painless 脚本。 +`remove_duplicates` | [RemoveDuplicatesTokenFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/miscellaneous/RemoveDuplicatesTokenFilter.html) | 删除位于同一位置的重复词元。 +`reverse` | [ReverseStringFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/reverse/ReverseStringFilter.html) | 反转词元流中每个词元对应的字符串。例如,词元 `dog` 变为 `god`。 +`shingle` | [ShingleFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/shingle/ShingleFilter.html) | 为词元流中的词元生成长度介于 `min_shingle_size` 和 `max_shingle_size` 之间的 shingle。shingle 与 n-gram 类似,但作用于单词而不是字母。例如,为一元组列表 [`contribute`, `to`, `opensearch`] 添加的双词 shingle 为 [`contribute to`, `to opensearch`]。 +`snowball` | N/A | 使用 [Snowball 生成的词干提取器](https://snowballstem.org/)对单词进行词干提取。你可以在 `language` 字段中为 `snowball` 词元过滤器使用以下语言:`Arabic`、`Armenian`、`Basque`、`Catalan`、`Danish`、`Dutch`、`English`、`Estonian`、`Finnish`、`French`、`German`、`German2`、`Hungarian`、`Irish`、`Italian`、`Kp`、`Lithuanian`、`Lovins`、`Norwegian`、`Porter`、`Portuguese`、`Romanian`、`Russian`、`Spanish`、`Swedish`、`Turkish`。 +`stemmer` | N/A | 为 `language` 字段中的以下语言提供算法词干提取:`arabic`、`armenian`、`basque`、`bengali`、`brazilian`、`bulgarian`、`catalan`、`czech`、`danish`、`dutch`、`dutch_kp`、`english`、`light_english`、`lovins`、`minimal_english`、`porter2`、`possessive_english`、`estonian`、`finnish`、`light_finnish`、`french`、`light_french`、`minimal_french`、`galician`、`minimal_galician`、`german`、`german2`、`light_german`、`minimal_german`、`greek`、`hindi`、`hungarian`、`light_hungarian`、`indonesian`、`irish`、`italian`、`light_italian`、`latvian`、`Lithuanian`、`norwegian`、`light_norwegian`、`minimal_norwegian`、`light_nynorsk`、`minimal_nynorsk`、`portuguese`、`light_portuguese`、`minimal_portuguese`、`portuguese_rslp`、`romanian`、`russian`、`light_russian`、`sorani`、`spanish`、`light_spanish`、`swedish`、`light_swedish`、`turkish`。 +`stemmer_override` | N/A | 通过应用自定义映射来覆盖词干提取算法,使指定的词项不被提取词干。 +`stop` | [StopFilter](https://lucene.apache.org/core/8_7_0/core/org/apache/lucene/analysis/StopFilter.html) | 从词元流中删除停用词。 +`synonym` | N/A | 为分析过程提供同义词列表。同义词列表通过配置文件提供。 +`synonym_graph` | N/A | 为分析过程提供同义词列表,包括多词同义词。 +`trim` | [TrimFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/miscellaneous/TrimFilter.html) | 去除流中每个词元开头和结尾的空白字符。 +`truncate` | [TruncateTokenFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/miscellaneous/TruncateTokenFilter.html) | 截断长度超过指定字符数限制的词元。 +`unique` | N/A | 通过从流中删除重复词元,确保每个词元都是唯一的。 +`uppercase` | [UpperCaseFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/core/LowerCaseFilter.html) | 将词元转换为大写。 +`word_delimiter` | [WordDelimiterFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/miscellaneous/WordDelimiterFilter.html) | 在非字母数字字符处拆分词元,并根据指定的规则执行规范化。 +`word_delimiter_graph` | [WordDelimiterGraphFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/miscellaneous/WordDelimiterGraphFilter.html) | 在非字母数字字符处拆分词元,并根据指定的规则执行规范化。为跨多个位置的词元分配 `positionLength` 属性。 diff --git a/i18n/zh/analyzers/tokenizers/index.md b/i18n/zh/analyzers/tokenizers/index.md new file mode 100644 index 00000000..3874c119 --- /dev/null +++ b/i18n/zh/analyzers/tokenizers/index.md @@ -0,0 +1,55 @@ +--- +title: 分词器 +--- + +# 分词器 + +分词器(Tokenizer)接收字符流,并将文本拆分为单独的*词元(Token)*。词元由一个词项(通常是一个单词)以及关于该词项的元数据组成。例如,分词器可以按空白字符拆分文本,使文本 `Actions speak louder than words.` 变为 [`Actions`, `speak`, `louder`, `than`, `words.`]。 + +分词器的输出是一个词元流。分词器还会维护以下关于词元的元数据: + +- 每个词元的**顺序**或**位置**:此信息用于单词和短语的邻近查询。 +- 词元在文本中的起始和结束位置(**偏移量**):此信息用于高亮显示搜索词。 +- 词元的**类型**:一些分词器(例如 `standard`)会按类型对词元进行分类,例如 `` 或 ``。较简单的分词器(例如 `letter`)只会把词元归类为 `word` 类型。 + +你可以使用分词器来定义自定义分析器(Analyzer)。 + +## 内置分词器 + +下表列出了 OpenSearch 提供的内置分词器。 + +### 单词分词器 + +单词分词器将全文解析为单词。 + +分词器 | 描述 | 示例 +:--- | :--- | :--- +`standard` | - 在单词边界处将字符串解析为词元
- 移除大部分标点符号 | `It’s fun to contribute a brand-new PR or 2 to OpenSearch!`
变为
[`It’s`, `fun`, `to`, `contribute`, `a`,`brand`, `new`, `PR`, `or`, `2`, `to`, `OpenSearch`] +`letter` | - 在任何非字母字符处将字符串解析为词元
- 移除非字母字符 | `It’s fun to contribute a brand-new PR or 2 to OpenSearch!`
变为
[`It`, `s`, `fun`, `to`, `contribute`, `a`,`brand`, `new`, `PR`, `or`, `to`, `OpenSearch`] +`lowercase` | - 在任何非字母字符处将字符串解析为词元
- 移除非字母字符
- 将词项转换为小写 | `It’s fun to contribute a brand-new PR or 2 to OpenSearch!`
变为
[`it`, `s`, `fun`, `to`, `contribute`, `a`,`brand`, `new`, `pr`, `or`, `to`, `opensearch`] +`whitespace` | - 在空白字符处将字符串解析为词元 | `It’s fun to contribute a brand-new PR or 2 to OpenSearch!`
变为
[`It’s`, `fun`, `to`, `contribute`, `a`,`brand-new`, `PR`, `or`, `2`, `to`, `OpenSearch!`] +`uax_url_email` | - 与 standard 分词器类似
- 与 standard 分词器不同的是,它会将 URL 和电子邮件地址保留为单个词项 | `It’s fun to contribute a brand-new PR or 2 to OpenSearch opensearch-project@github.com!`
变为
[`It’s`, `fun`, `to`, `contribute`, `a`,`brand`, `new`, `PR`, `or`, `2`, `to`, `OpenSearch`, `opensearch-project@github.com`] +`classic` | - 在以下位置将字符串解析为词元:
  - 后跟空白字符的标点符号
  - 连字符(如果词项不包含数字)
- 移除标点符号
- 将 URL 和电子邮件地址保留为单个词项 | `Part number PA-35234, single-use product (128.32)`
变为
[`Part`, `number`, `PA-35234`, `single`, `use`, `product`, `128.32`] +`thai` | - 将泰文文本解析为词项 | `สวัสดีและยินดีต`
变为
[`สวัสด`, `และ`, `ยินดี`, `ต`] + +### 部分单词分词器 + +部分单词分词器将文本解析为单词,并生成这些单词的片段,用于部分单词匹配。 + +分词器 | 描述 | 示例 +:--- | :--- | :--- +`ngram`| - 在指定字符(例如标点符号或空白字符)处将字符串解析为单词,并为每个单词生成 n-gram | `My repo`
变为
[`M`, `My`, `y`, `y `,  ,  r, `r`, `re`, `e`, `ep`, `p`, `po`, `o`]
因为默认的 n-gram 长度为 1--2 个字符 +`edge_ngram` | - 在指定字符(例如标点符号或空白字符)处将字符串解析为单词,并为每个单词生成 edge n-gram(从单词开头开始的 n-gram) | `My repo`
变为
[`M`, `My`]
因为默认的 n-gram 长度为 1--2 个字符 + +### 结构化文本分词器 + +结构化文本分词器用于解析结构化文本,例如标识符、电子邮件地址、路径或邮政编码。 + +分词器 | 描述 | 示例 +:--- | :--- | :--- +`keyword` | - 不执行任何操作的分词器
- 原样输出整个字符串
- 可以与词元过滤器(例如 lowercase)组合使用来规范化词项 | `My repo`
变为
`My repo` +`pattern` | - 使用正则表达式模式按单词分隔符将文本解析为词项,或将匹配的文本捕获为词项
- 使用 [Java 正则表达式](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html) | `https://opensearch.org/forum`
变为
[`https`, `opensearch`, `org`, `forum`],因为默认情况下该分词器在单词边界(`\W+`)处拆分词项
可以配置正则表达式模式 +`simple_pattern` | - 使用正则表达式模式将匹配的文本作为词项返回
- 使用 [Lucene 正则表达式](https://lucene.apache.org/core/8_7_0/core/org/apache/lucene/util/automaton/RegExp.html)
- 比 `pattern` 分词器更快,因为它使用的是 `pattern` 分词器正则表达式的一个子集 | 默认返回空数组
必须配置模式,因为模式默认为空字符串 +`simple_pattern_split` | - 使用正则表达式模式在匹配处拆分文本,而不是将匹配项作为词项返回
- 使用 [Lucene 正则表达式](https://lucene.apache.org/core/8_7_0/core/org/apache/lucene/util/automaton/RegExp.html)
- 比 `pattern` 分词器更快,因为它使用的是 `pattern` 分词器正则表达式的一个子集 | 默认不执行任何操作
必须配置模式 +`char_group` | - 按一组可配置的字符进行解析
- 比运行正则表达式的分词器更快 | 默认不执行任何操作
必须配置字符列表 +`path_hierarchy` | - 按路径分隔符(默认为 `/`)解析文本,并返回树形层级中每个组成部分的完整路径 | `one/two/three`
变为
[`one`, `one/two`, `one/two/three`] diff --git a/i18n/zh/field-types/index.md b/i18n/zh/field-types/index.md new file mode 100644 index 00000000..2a16b642 --- /dev/null +++ b/i18n/zh/field-types/index.md @@ -0,0 +1,210 @@ +--- +title: 映射和字段类型 +--- + +# 映射和字段类型 + +你可以通过创建*映射(Mapping)* 来定义文档及其字段的存储和索引方式。映射指定了文档的字段列表。文档中的每个字段都有一个*字段类型(Field Type)*,它定义了该字段所包含数据的类型。例如,你可能希望指定 `year` 字段的类型为 `date`。要了解更多信息,请参阅[支持的字段类型](/field-types/supported-field-types/)。 + +如果你刚开始构建集群和数据,可能还不确定数据应该如何存储。在这种情况下,可以使用动态映射,让 OpenSearch 动态地添加数据及其字段。但是,如果你清楚地知道数据属于哪些类型,并希望强制执行这一标准,则可以使用显式映射。 + +例如,如果你想指明 `year` 的类型应为 `text` 而不是 `integer`,而 `age` 应为 `integer`,就可以使用显式映射来实现。如果使用动态映射,OpenSearch 可能会把 `year` 和 `age` 都解释为整数。 + +本节提供了一个示例,演示如何创建索引映射,以及如何向其中添加一个会经过 ip_range 验证的文档。 + +--- +## 动态映射 + +索引文档时,OpenSearch 会通过动态映射自动添加字段。你也可以显式地向索引映射中添加字段。 + +#### 动态映射类型 + +类型 | 描述 +:--- | :--- +null | `null` 字段无法被索引或搜索。当字段被设置为 null 时,OpenSearch 会将其视为该字段没有值。 +boolean | OpenSearch 接受 `true` 和 `false` 作为布尔值。空字符串等同于 `false.` +float | 单精度 32 位浮点数。 +double | 双精度 64 位浮点数。 +integer | 有符号 32 位数字。 +object | 对象是标准的 JSON 对象,可以拥有自己的字段和映射。例如,`movies` 对象可以包含 `title`、`year` 和 `director` 等其他属性。 +array | OpenSearch 中的数组只能存储一种类型的值,例如只包含整数或只包含字符串的数组。空数组会被视为没有值的字段。 +text | 表示全文值的字符串字符序列。 +keyword | 结构化字符组成的字符串序列,例如电子邮件地址或邮政编码。 +date detection string | 默认启用。如果新的字符串字段匹配日期格式,则该字符串会作为 `date` 字段处理。例如,`date: "2012/03/11"` 会被作为日期处理。 +numeric detection string | 如果禁用,OpenSearch 可能会把本应作为数字处理的数值自动作为字符串处理。启用后,OpenSearch 可以将字符串处理为 `long`、`integer`、`short`、`byte`、`double`、`float`、`half_float`、`scaled_float` 和 `unsigned_long`。默认禁用。 + +## 显式映射 + +如果你确切知道字段需要的数据类型,可以在创建索引时在请求体中指定。 + +```json +PUT sample-index1 +{ + "mappings": { + "properties": { + "year": { "type" : "text" }, + "age": { "type" : "integer" }, + "director":{ "type" : "text" } + } + } +} +``` + +### 响应 +```json +{ + "acknowledged": true, + "shards_acknowledged": true, + "index": "sample-index1" +} +``` + +要向现有索引或数据流添加映射,可以使用 `PUT` 或 `POST` HTTP 方法向 `_mapping` 端点发送请求: + +```json +POST sample-index1/_mapping +{ + "properties": { + "year": { "type" : "text" }, + "age": { "type" : "integer" }, + "director":{ "type" : "text" } + } +} +``` + +::: info 注意 +你不能更改现有字段的映射,只能修改该字段的映射参数。 +::: + +--- +## 映射用法示例 + +以下示例演示如何创建映射,指定 OpenSearch 忽略所有 IP 地址格式错误、不符合 [`ip`](/field-types/supported-field-types/ip) 数据类型的文档。这可以通过将 `ignore_malformed` 参数设置为 `true` 来实现。 + +### 创建带有 `ip` 映射的索引 + +要创建索引,请使用 PUT 请求: + +```json +PUT /test-index +{ + "mappings" : { + "properties" : { + "ip_address" : { + "type" : "ip", + "ignore_malformed": true + } + } + } +} +``` + +你可以向索引中添加一个 IP 地址格式错误的文档: + +```json +PUT /test-index/_doc/1 +{ + "ip_address" : "malformed ip address" +} +``` + +由于 `ignore_malformed` 设置为 true,这个被索引的 IP 地址不会引发错误。 + +你可以使用以下请求查询该索引: + +```json +GET /test-index/_search +``` + +响应显示,被索引文档中的 `ip_address` 字段被忽略了: + +```json +{ + "took": 14, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "test-index", + "_id": "1", + "_score": 1, + "_ignored": [ + "ip_address" + ], + "_source": { + "ip_address": "malformed ip address" + } + } + ] + } +} +``` + +## 获取映射 + +要获取一个或多个索引的所有映射,请使用以下请求: + +```json +GET /_mapping +``` + +在上述请求中,`` 可以是一个索引名称,也可以是以逗号分隔的索引名称列表。 + +要获取所有索引的所有映射,请使用以下请求: + +```json +GET _mapping +``` + +要获取特定字段的映射,请提供索引名称和字段名称: + +```json +GET _mapping/field/ +GET //_mapping/field/ +``` + +`` 和 `` 都可以指定为单个值或以逗号分隔的列表。 + +例如,以下请求检索 `sample-index1` 中 `year` 和 `age` 字段的映射: + +```json +GET sample-index1/_mapping/field/year,age +``` + +响应包含指定的字段: + +```json +{ + "sample-index1" : { + "mappings" : { + "year" : { + "full_name" : "year", + "mapping" : { + "year" : { + "type" : "text" + } + } + }, + "age" : { + "full_name" : "age", + "mapping" : { + "age" : { + "type" : "integer" + } + } + } + } + } +} +``` diff --git a/i18n/zh/field-types/supported-field-types/alias.md b/i18n/zh/field-types/supported-field-types/alias.md new file mode 100644 index 00000000..2e193577 --- /dev/null +++ b/i18n/zh/field-types/supported-field-types/alias.md @@ -0,0 +1,86 @@ +--- +title: 别名 +--- + +# 别名字段类型 + +别名(Alias)字段类型为现有字段创建另一个名称。你可以在[搜索](#using-aliases-in-search-api-operations)和[字段能力](#using-aliases-in-field-capabilities-api-operations) API 操作中使用别名,但存在一些[例外情况](#exceptions)。要设置[别名](#alias-field),需要在 `path` 参数中指定[原始字段](#original-field)的名称。 + +## 示例 + +```json +PUT movies +{ + "mappings" : { + "properties" : { + "year" : { + "type" : "date" + }, + "release_date" : { + "type" : "alias", + "path" : "year" + } + } + } +} +``` + +## 参数 + +参数 | 描述 +:--- | :--- +`path` | 原始字段的完整路径,包括所有父对象。例如 parent.child.field_name。必需。 + +## 别名字段 + +别名字段必须遵守以下规则: + +- 一个别名字段只能有一个原始字段。 +- 在嵌套对象中,别名必须与原始字段处于相同的嵌套层级。 + +::: info 注意 +要更改别名引用的字段,请更新映射(Mapping)。请注意,之前存储的任何 percolator 查询中的别名仍会引用原来的字段。 +::: + +## 原始字段 + +别名的原始字段必须遵守以下规则: +- 原始字段必须在创建别名之前创建。 +- 原始字段不能是对象或另一个别名。 + +## 在搜索 API 操作中使用别名 + +你可以在搜索 API 的以下读取操作中使用别名: +- 查询 +- 排序 +- 聚合 +- `stored_fields` +- `docvalue_fields` +- 建议(Suggestion) +- 高亮 +- 访问字段值的脚本 + +## 在字段能力 API 操作中使用别名 + +要在字段能力 API 中使用别名,请在 fields 参数中指定该别名。 + +```json +GET movies/_field_caps?fields=release_date +``` + +## 例外情况 + +在以下情况下不能使用别名: +- 在写入请求中,例如更新请求。 +- 在多字段中,或作为 `copy_to` 的目标。 +- 作为用于过滤结果的 _source 参数。 +- 在接受字段名的 API 中,例如词项向量(term vectors)。 +- 在 `terms`、`more_like_this` 和 `geo_shape` 查询中(检索文档时不支持别名)。 + +## 通配符 + +在搜索和字段能力的通配符查询中,原始字段和别名都会与通配符模式进行匹配。 + +```json +GET movies/_field_caps?fields=release* +``` diff --git a/i18n/zh/field-types/supported-field-types/autocomplete.md b/i18n/zh/field-types/supported-field-types/autocomplete.md new file mode 100644 index 00000000..21b0442d --- /dev/null +++ b/i18n/zh/field-types/supported-field-types/autocomplete.md @@ -0,0 +1,12 @@ +--- +title: 自动补全字段类型 +--- + +# 自动补全字段类型 + +下表列出了 OpenSearch 支持的所有自动补全字段类型(Field Type)。 + +字段数据类型 | 描述 +:--- | :--- +[`completion`](/field-types/supported-field-types/completion) | 一种补全建议器,使用前缀补全提供自动补全功能。使用此功能之前,需要将所有可能的补全项列表上传到索引中。 +[`search_as_you_type`](/field-types/supported-field-types/search-as-you-type) | 同时使用前缀补全和中缀补全,提供边输入边搜索(search-as-you-type)功能。 diff --git a/i18n/zh/field-types/supported-field-types/binary.md b/i18n/zh/field-types/supported-field-types/binary.md new file mode 100644 index 00000000..1f2bfc19 --- /dev/null +++ b/i18n/zh/field-types/supported-field-types/binary.md @@ -0,0 +1,46 @@ +--- +title: 二进制 +--- + +# 二进制字段类型 + +二进制(binary)字段类型包含以 [Base64](https://en.wikipedia.org/wiki/Base64) 编码的二进制值,该值不可搜索。 + +## 示例 + +创建一个包含二进制字段的映射: + +```json +PUT testindex +{ + "mappings" : { + "properties" : { + "binary_value" : { + "type" : "binary" + } + } + } +} +``` + +索引一个包含二进制值的文档: + +```json +PUT testindex/_doc/1 +{ + "binary_value" : "bGlkaHQtd29rfx4=" +} +``` + +::: info 注意 +使用 `=` 作为填充字符。不允许包含内嵌的换行符。 +::: + +## 参数 + +下表列出了二进制字段类型接受的参数。所有参数均为可选。 + +参数 | 描述 +:--- | :--- +`doc_values` | 一个布尔值,指定是否应将该字段存储在磁盘上,以便用于聚合、排序或脚本。可选。默认值为 `true`。 +`store` | 一个布尔值,指定是否应存储该字段值,使其可以独立于 _source 字段单独检索。可选。默认值为 `false`。 diff --git a/i18n/zh/field-types/supported-field-types/boolean.md b/i18n/zh/field-types/supported-field-types/boolean.md new file mode 100644 index 00000000..13ae597c --- /dev/null +++ b/i18n/zh/field-types/supported-field-types/boolean.md @@ -0,0 +1,146 @@ +--- +title: 布尔 +--- + +# 布尔字段类型 + +布尔(Boolean)字段类型接受 `true` 或 `false` 值,或者 `"true"` 或 `"false"` 字符串。你也可以传入空字符串(`""`)来代替 `false` 值。 + +## 示例 + +创建一个映射,其中 a、b 和 c 都是布尔字段: + +```json +PUT testindex +{ + "mappings" : { + "properties" : { + "a" : { + "type" : "boolean" + }, + "b" : { + "type" : "boolean" + }, + "c" : { + "type" : "boolean" + } + } + } +} +``` + +索引一个包含布尔值的文档: + +```json +PUT testindex/_doc/1 +{ + "a" : true, + "b" : "true", + "c" : "" +} +``` + +结果是,`a` 和 `b` 会被设置为 `true`,`c` 会被设置为 `false`。 + +搜索 `c` 为 false 的所有文档: + +```json +GET testindex/_search +{ + "query": { + "term" : { + "c" : false + } + } +} +``` + +## 参数 + +下表列出了布尔字段类型接受的参数。所有参数均为可选。 + +参数 | 描述 +:--- | :--- +`boost` | 一个浮点值,指定该字段对相关性评分(Relevance Score)的权重。大于 1.0 的值会提高该字段的相关性,介于 0.0 和 1.0 之间的值会降低该字段的相关性。默认值为 1.0。 +`doc_values` | 一个布尔值,指定是否应将该字段存储在磁盘上,以便用于聚合、排序或脚本。默认值为 `true`。 +`index` | 一个布尔值,指定该字段是否可搜索。默认值为 `true`。 +`meta` | 接受该字段的元数据。 +[`null_value`](/field-types/supported-field-types/#null-value) | 用于代替 `null` 的值,必须与该字段的类型相同。如果未指定此参数,当字段值为 `null` 时,该字段被视为缺失。默认值为 `null`。 +`store` | 一个布尔值,指定是否应存储该字段值,使其可以独立于 _source 字段单独检索。默认值为 `false`。 + +## 聚合和脚本中的布尔值 + +在对布尔字段进行的聚合(Aggregation)中,`key` 返回数值(`true` 为 1,`false` 为 0),`key_as_string` 返回字符串(`"true"` 或 `"false"`)。脚本对布尔值返回 `true` 和 `false`。 + +### 示例 {#example-1} + +对字段 `a` 运行 terms 聚合查询: + +```json +GET testindex/_search +{ + "aggs": { + "agg1": { + "terms": { + "field": "a" + } + } + }, + "script_fields": { + "a": { + "script": { + "lang": "painless", + "source": "doc['a'].value" + } + } + } +} +``` + +脚本返回的 `a` 的值为 `true`,`key` 返回的 `a` 的值为 `1`,`key_as_string` 返回的 `a` 的值为 `"true"`: + +```json +{ + "took" : 1133, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "testindex", + "_type" : "_doc", + "_id" : "1", + "_score" : 1.0, + "fields" : { + "a" : [ + true + ] + } + } + ] + }, + "aggregations" : { + "agg1" : { + "doc_count_error_upper_bound" : 0, + "sum_other_doc_count" : 0, + "buckets" : [ + { + "key" : 1, + "key_as_string" : "true", + "doc_count" : 1 + } + ] + } + } +} +``` diff --git a/i18n/zh/field-types/supported-field-types/completion.md b/i18n/zh/field-types/supported-field-types/completion.md new file mode 100644 index 00000000..2bf797b0 --- /dev/null +++ b/i18n/zh/field-types/supported-field-types/completion.md @@ -0,0 +1,378 @@ +--- +title: 补全 +--- + +# 补全字段类型 + +补全(completion)字段类型通过补全建议器(completion suggester)提供自动补全功能。补全建议器是一种前缀建议器,因此只匹配文本的开头部分。补全建议器会创建一个内存数据结构,查找速度更快,但会增加内存占用。使用此功能之前,需要将所有可能的补全项列表上传到索引(Index)中。 + +## 示例 + +创建一个包含补全字段的映射(Mapping): + +```json +PUT chess_store +{ + "mappings": { + "properties": { + "suggestions": { + "type": "completion" + }, + "product": { + "type": "keyword" + } + } + } +} +``` + +将建议项索引到 OpenSearch 中: + +```json +PUT chess_store/_doc/1 +{ + "suggestions": { + "input": ["Books on openings", "Books on endgames"], + "weight" : 10 + } +} +``` + +## 参数 + +下表列出了补全字段接受的参数。 + +参数 | 描述 +:--- | :--- +`input` | 可能的补全项列表,可以是字符串或字符串数组。不能包含 `\u0000`(null)、`\u001f`(信息分隔符一)或 `\u001e`(信息分隔符二)。必需。 +`weight` | 用于对建议项进行排名的正整数或正整数字符串。可选。 + +可以按如下方式索引多个建议项: + +```json +PUT chess_store/_doc/2 +{ + "suggestions": [ + { + "input": "Chess set", + "weight": 20 + }, + { + "input": "Chess pieces", + "weight": 10 + }, + { + "input": "Chess board", + "weight": 5 + } + ] +} +``` + +你也可以使用以下简写形式(注意,在这种写法中不能提供 `weight` 参数): + +```json +PUT chess_store/_doc/3 +{ + "suggestions" : [ "Chess clock", "Chess timer" ] +} +``` + +## 查询补全字段类型 + +要查询补全字段类型,请指定要搜索的前缀以及用于查找建议项的字段名称。 + +在索引中查询以单词 "chess" 开头的建议项: + +```json +GET chess_store/_search +{ + "suggest": { + "product-suggestions": { + "prefix": "chess", + "completion": { + "field": "suggestions" + } + } + } +} +``` + +响应包含自动补全建议项: + +```json +{ + "took" : 3, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 0, + "relation" : "eq" + }, + "max_score" : null, + "hits" : [ ] + }, + "suggest" : { + "product-suggestions" : [ + { + "text" : "chess", + "offset" : 0, + "length" : 5, + "options" : [ + { + "text" : "Chess set", + "_index" : "chess_store", + "_type" : "_doc", + "_id" : "2", + "_score" : 20.0, + "_source" : { + "suggestions" : [ + { + "input" : "Chess set", + "weight" : 20 + }, + { + "input" : "Chess pieces", + "weight" : 10 + }, + { + "input" : "Chess board", + "weight" : 5 + } + ] + } + }, + { + "text" : "Chess clock", + "_index" : "chess_store", + "_type" : "_doc", + "_id" : "3", + "_score" : 1.0, + "_source" : { + "suggestions" : [ + "Chess clock", + "Chess timer" + ] + } + } + ] + } + ] + } +} +``` + +在响应中,`_score` 字段包含索引时设置的 `weight` 参数值。`text` 字段填充的是建议项的 `input` 参数。 + +默认情况下,响应包含整个文档(Document),包括 `_source` 字段,这可能会影响性能。要只返回 `suggestions` 字段,可以在 `_source` 参数中指定。你还可以通过指定 `size` 参数来限制返回的建议项数量。 + +```json +GET chess_store/_search +{ + "_source": "suggestions", + "suggest": { + "product-suggestions": { + "prefix": "chess", + "completion": { + "field": "suggestions", + "size" : 3 + } + } + } +} +``` + +响应包含建议项: + +```json +{ + "took" : 5, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 0, + "relation" : "eq" + }, + "max_score" : null, + "hits" : [ ] + }, + "suggest" : { + "product-suggestions" : [ + { + "text" : "chess", + "offset" : 0, + "length" : 5, + "options" : [ + { + "text" : "Chess set", + "_index" : "chess_store", + "_type" : "_doc", + "_id" : "2", + "_score" : 20.0, + "_source" : { + "suggestions" : [ + { + "input" : "Chess set", + "weight" : 20 + }, + { + "input" : "Chess pieces", + "weight" : 10 + }, + { + "input" : "Chess board", + "weight" : 5 + } + ] + } + }, + { + "text" : "Chess clock", + "_index" : "chess_store", + "_type" : "_doc", + "_id" : "3", + "_score" : 1.0, + "_source" : { + "suggestions" : [ + "Chess clock", + "Chess timer" + ] + } + } + ] + } + ] + } +} +``` + +::: info 注意 +要使用源过滤功能,请在 `_search` 端点上使用建议功能。`_suggest` 端点不支持源过滤。 +::: + +## 补全查询参数 + +下表列出了补全建议器查询接受的参数。 + +参数 | 描述 +:--- | :--- +`field` | 一个字符串,指定要在其上运行查询的字段。必需。 +`size` | 一个整数,指定返回建议项的最大数量。可选。默认值为 5。 +`skip_duplicates` | 一个布尔值,指定是否跳过重复的建议项。可选。默认值为 `false`。 + +## 模糊补全查询 + +为了支持模糊匹配,可以为补全查询指定 `fuzziness` 参数。这样,即使用户输错了搜索词,补全查询仍会返回结果。此外,与查询匹配的前缀越长,文档的评分就越高。 + +```json +GET chess_store/_search +{ + "suggest": { + "product-suggestions": { + "prefix": "chesc", + "completion": { + "field": "suggestions", + "size" : 3, + "fuzzy" : { + "fuzziness" : "AUTO" + } + } + } + } +} +``` + +::: tip 提示 +要使用所有默认的模糊选项,请指定 `"fuzzy": {}` 或 `"fuzzy": true`。 +::: + +下表列出了模糊补全建议器查询接受的参数。所有参数均为可选。 + +参数 | 描述 +:--- | :--- +`fuzziness` | 模糊度可以设置为以下值之一:
1. 一个整数,指定此次编辑允许的最大 [Levenshtein 距离](https://en.wikipedia.org/wiki/Levenshtein_distance)。
2. `AUTO`:0–2 个字符的字符串必须精确匹配,3–5 个字符的字符串允许 1 次编辑,超过 5 个字符的字符串允许 2 次编辑。
默认值为 `AUTO`。 +`min_length` | 一个整数,指定开始返回建议项时输入所需的最小长度。如果搜索词短于 `min_length`,则不返回任何建议项。默认值为 3。 +`prefix_length` | 一个整数,指定开始返回建议项时匹配前缀所需的最小长度。如果长度为 `prefix_length` 的前缀不匹配,即使搜索词仍在 Levenshtein 距离之内,也不会返回任何建议项。默认值为 1。 +`transpositions` | 一个布尔值,指定是否将换位(相邻字符互换)计为一次编辑而不是两次。示例:建议项的 `input` 参数为 `abcde`,`fuzziness` 为 1。如果 `transpositions` 设置为 `true`,则 `abdce` 会匹配;如果 `transpositions` 设置为 `false`,则 `abdce` 不会匹配。默认值为 `true`。 +`unicode_aware` | 一个布尔值,指定在计算编辑距离、换位和长度时是否使用 Unicode 码位。如果 `unicode_aware` 设置为 `true`,计算速度会较慢。默认值为 `false`,此时以字节为单位计算距离。 + +## 正则表达式查询 + +你可以使用正则表达式来定义补全建议器查询的前缀。 + +例如,要搜索以 "a" 开头且后面某处包含 "d" 的字符串,请使用以下查询: + +```json +GET chess_store/_search +{ + "suggest": { + "product-suggestions": { + "regex": "a.*d", + "completion": { + "field": "suggestions" + } + } + } +} +``` + +响应匹配了字符串 "abcde": + +```json +{ + "took" : 2, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 0, + "relation" : "eq" + }, + "max_score" : null, + "hits" : [ ] + }, + "suggest" : { + "product-suggestions" : [ + { + "text" : "a.*d", + "offset" : 0, + "length" : 4, + "options" : [ + { + "text" : "abcde", + "_index" : "chess_store", + "_type" : "_doc", + "_id" : "2", + "_score" : 20.0, + "_source" : { + "suggestions" : [ + { + "input" : "abcde", + "weight" : 20 + } + ] + } + } + ] + } + ] + } +} +``` diff --git a/i18n/zh/field-types/supported-field-types/date-nanos.md b/i18n/zh/field-types/supported-field-types/date-nanos.md new file mode 100644 index 00000000..c2fa49dd --- /dev/null +++ b/i18n/zh/field-types/supported-field-types/date-nanos.md @@ -0,0 +1,278 @@ +--- +title: 纳秒日期 +--- + +# 纳秒日期字段类型 + +`date_nanos` 字段类型与 [`date`](/field-types/supported-field-types/date) 字段类型类似,都用于保存日期。不同之处在于,`date` 以毫秒精度存储日期,而 `date_nanos` 以纳秒精度存储日期。日期存储为 `long` 值,对应自纪元(epoch)以来的纳秒数。因此,支持的日期范围大约为 1970 年至 2262 年。 + +对 `date_nanos` 字段的查询(Query)会被转换为对字段值 `long` 表示形式的范围查询。然后,存储字段和聚合(Aggregation)结果会使用该字段上设置的格式转换为字符串。 + +::: info 注意 +`date_nanos` 字段支持 `date` 所支持的全部[格式](/field-types/supported-field-types/date#formats)和[参数](/field-types/supported-field-types/date#parameters)。可以使用多个格式,用 `||` 分隔。 +::: + +对于 `date_nanos` 字段,可以使用 `strict_date_optional_time_nanos` 格式来保留纳秒精度。如果将字段映射为 `date_nanos` 时没有指定格式,则默认格式为 `strict_date_optional_time||epoch_millis`,允许以 `strict_date_optional_time` 或 `epoch_millis` 格式传入值。`strict_date_optional_time` 格式支持纳秒精度的日期,而 `epoch_millis` 格式只支持毫秒精度的日期。 + +## 示例 + +创建一个映射(Mapping),其中 `date` 字段的类型为 `date_nanos`,格式为 `strict_date_optional_time_nanos`: + +```json +PUT testindex/_mapping +{ + "properties": { + "date": { + "type": "date_nanos", + "format" : "strict_date_optional_time_nanos" + } + } +} +``` + +向索引中索引两个文档(Document): + +```json +PUT testindex/_doc/1 +{ "date": "2022-06-15T10:12:52.382719622Z" } +``` + +```json +PUT testindex/_doc/2 +{ "date": "2022-06-15T10:12:52.382719624Z" } +``` + +可以使用 range 查询搜索日期范围: + +```json +GET testindex/_search +{ + "query": { + "range": { + "date": { + "gte": "2022-06-15T10:12:52.382719621Z", + "lte": "2022-06-15T10:12:52.382719623Z" + } + } + } +} +``` + +响应中包含日期位于指定范围内的文档: + +```json +{ + "took": 43, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "testindex", + "_id": "1", + "_score": 1, + "_source": { + "date": "2022-06-15T10:12:52.382719622Z" + } + } + ] + } +} +``` + +查询包含 `date_nanos` 字段的文档时,可以使用 `fields` 或 `docvalue_fields`: + +```json +GET testindex/_search +{ + "fields": ["date"] +} +``` + +```json +GET testindex/_search +{ + "docvalue_fields" : [ + { + "field" : "date" + } + ] +} +``` + +上述任一查询的响应都包含两个已索引的文档: + +```json +{ + "took": 4, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "testindex", + "_id": "1", + "_score": 1, + "_source": { + "date": "2022-06-15T10:12:52.382719622Z" + }, + "fields": { + "date": [ + "2022-06-15T10:12:52.382719622Z" + ] + } + }, + { + "_index": "testindex", + "_id": "2", + "_score": 1, + "_source": { + "date": "2022-06-15T10:12:52.382719624Z" + }, + "fields": { + "date": [ + "2022-06-15T10:12:52.382719624Z" + ] + } + } + ] + } +} +``` + +可以按如下方式对 `date_nanos` 字段进行排序: + +```json +GET testindex/_search +{ + "sort": { + "date": "asc" + } +} +``` + +响应中包含排序后的文档: + +```json +{ + "took": 5, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": null, + "hits": [ + { + "_index": "testindex", + "_id": "1", + "_score": null, + "_source": { + "date": "2022-06-15T10:12:52.382719622Z" + }, + "sort": [ + 1655287972382719700 + ] + }, + { + "_index": "testindex", + "_id": "2", + "_score": null, + "_source": { + "date": "2022-06-15T10:12:52.382719624Z" + }, + "sort": [ + 1655287972382719700 + ] + } + ] + } +} +``` + +还可以使用 Painless 脚本访问字段的纳秒部分: + +```json +GET testindex/_search +{ + "script_fields" : { + "my_field" : { + "script" : { + "lang" : "painless", + "source" : "doc['date'].value.nano" + } + } + } +} +``` + +响应中只包含字段的纳秒部分: + +```json +{ + "took": 4, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "testindex", + "_id": "1", + "_score": 1, + "fields": { + "my_field": [ + 382719622 + ] + } + }, + { + "_index": "testindex", + "_id": "2", + "_score": 1, + "fields": { + "my_field": [ + 382719624 + ] + } + } + ] + } +} +``` diff --git a/i18n/zh/field-types/supported-field-types/date.md b/i18n/zh/field-types/supported-field-types/date.md new file mode 100644 index 00000000..8526c8ee --- /dev/null +++ b/i18n/zh/field-types/supported-field-types/date.md @@ -0,0 +1,346 @@ +--- +title: Date +--- + +# Date 字段类型 + +在 OpenSearch 中,日期可以用以下任意一种形式表示: + +- 一个 long 值,对应自纪元(epoch)以来的毫秒数(该值必须为非负数)。日期在内部以这种形式存储。 +- 一个格式化的字符串。 +- 一个整数值,对应自纪元以来的秒数(该值必须为非负数)。 + +::: info 注意 +如需表示日期范围,可以使用日期[范围字段类型](/field-types/supported-field-types/range)。 +::: + +## 示例 + +创建一个包含日期字段和两种日期格式的映射(Mapping): + +```json +PUT testindex +{ + "mappings" : { + "properties" : { + "release_date" : { + "type" : "date", + "format" : "strict_date_optional_time||epoch_millis" + } + } + } +} +``` + +## 参数 + +下表列出了日期字段类型接受的参数。所有参数均为可选。 + +参数 | 描述 +:--- | :--- +`boost` | 一个浮点值,指定该字段对相关性评分(Relevance Score)的权重。大于 1.0 的值会提高该字段的相关性,介于 0.0 和 1.0 之间的值会降低该字段的相关性。默认值为 1.0。 +`doc_values` | 一个布尔值,指定是否将该字段存储到磁盘上,以便用于聚合、排序或脚本。默认值为 `false`。 +`format` | 用于解析日期的格式。默认值为 `strict_date_time_no_millis||strict_date_optional_time||epoch_millis`。 +`ignore_malformed` | 一个布尔值,指定忽略格式错误的值而不抛出异常。默认值为 `false`。 +`index` | 一个布尔值,指定该字段是否可搜索。默认值为 `true`。 +`locale` | 一种与地区和语言相关的日期表示方式。默认值为 [`ROOT`](https://docs.oracle.com/javase/8/docs/api/java/util/Locale.html#ROOT)(与地区和语言无关的区域设置)。 +`meta` | 接受该字段的元数据。 +[`null_value`](/field-types/supported-field-types/#null-value) | 用于替代 `null` 的值,必须与字段类型相同。如果未指定此参数,当字段值为 `null` 时,该字段会被视为缺失。默认值为 `null`。 +`store` | 一个布尔值,指定是否存储字段值,以便能独立于 _source 字段单独检索。默认值为 `false`。 + +## 格式 + +OpenSearch 内置了多种日期格式,也可以创建自定义格式。可以指定多个日期格式,用 `||` 分隔。 + +## 默认格式 + +从 OpenSearch 2.12 开始,默认日期格式为 `strict_date_time_no_millis||strict_date_optional_time||epoch_millis`。如需将默认格式恢复为 `strict_date_optional_time||epoch_millis`(OpenSearch 2.11 及更早版本的默认格式),请将 `opensearch.experimental.optimization.datetime_formatter_caching.enabled` 功能标志设置为 `false`。有关启用和禁用功能标志的更多信息,请参阅[启用实验性功能](/install-and-configure/configuring-opensearch/experimental)。 + +## 内置格式 + +大多数日期格式都有一个对应的 `strict_` 版本。当格式以 `strict_` 开头时,日期的位数必须与格式中指定的位数完全一致。例如,如果格式设置为 `strict_year_month_day`(`"yyyy-MM-dd"`),则月和日都必须是两位数字。因此,`"2020-06-09"` 是有效的,而 `"2020-6-9"` 是无效的。 + +::: info 注意 +纪元(epoch)定义为 1970 年 1 月 1 日 00:00:00 UTC。 +::: + +::: info 注意 +y:年
+Y:[基于周的年份](https://en.wikipedia.org/wiki/ISO_8601#Week_dates)
+M:月
+w:[一年中的第几周](https://en.wikipedia.org/wiki/ISO_8601#Week_dates),从 01 到 53
+d:日
+D:一年中的第几天,从 001 到 365(闰年为 366)
+e:一周中的第几天,从 1(星期一)到 7(星期日)
+H:小时,从 0 到 23
+m:分钟
+s:秒
+S:秒的小数部分
+Z:时区偏移(例如 +0400、-0400、-04:00)
+::: + +### 数值日期格式 + +格式名称及描述 | 示例 +:--- | :--- +`epoch_millis`
自纪元以来的毫秒数。最小值为 -263,最大值为 263 − 1。 | 1553391286000 +`epoch_second`
自纪元以来的秒数。最小值为 -263 ÷ 1000,最大值为 (263 − 1) ÷ 1000。 | 1553391286 + +### 基本日期格式 + +基本日期格式的各组成部分之间没有分隔符。例如 "20190323"。 + +格式名称及描述 | 模式及示例 +:--- | :--- +**日期**| +`basic_date_time`
以 `T` 分隔的基本日期和时间。 | `"yyyyMMdd`T`HHmmss.SSSZ"`
`"20190323T213446.123-04:00"` +`basic_date_time_no_millis`
不含毫秒、以 `T` 分隔的基本日期和时间。 | `"yyyyMMdd`T`HHmmssZ"`
`"20190323T213446-04:00"` +`basic_date`
由四位数年份、两位数月份和两位数日期组成的日期。 | `"yyyyMMdd"
"20190323"` +**时间** | +`basic_time`
由两位数小时、两位数分钟、两位数秒、三位数毫秒和时区偏移组成的时间。 |`"HHmmss.SSSZ"`
`"213446.123-04:00"` +`basic_time_no_millis`
不含毫秒的基本时间。 | `"HHmmssZ"`
`"213446-04:00"` +**T 时间** | +`basic_t_time`
以 `T` 开头的基本时间。 | `"`T`HHmmss.SSSZ"`
`"T213446.123-04:00"` +`basic_t_time_no_millis`
不含毫秒、以 `T` 开头的基本时间。 | `"`T`HHmmssZ"`
`"T213446-04:00"` +**序数日期** | +`basic_ordinal_date_time`
完整的序数日期和时间。 | `"yyyyDDD`T`HHmmss.SSSZ"`
`"2019082T213446.123-04:00"` +`basic_ordinal_date_time_no_millis`
不含毫秒的完整序数日期和时间。 | `"yyyyDDD`T`HHmmssZ"`
`"2019082T213446-04:00"` +`basic_ordinal_date`
由四位数年份和三位数的年内序数日组成的日期。 | `"yyyyDDD"`
`"2019082"` +**基于周的日期** | +`basic_week_date_time`
`strict_basic_week_date_time`
以 `T` 分隔的完整的基于周的日期和时间。 | `"YYYY`W`wwe`T`HHmmss.SSSZ"`
`"2019W126213446.123-04:00"` +`basic_week_date_time_no_millis`
`strict_basic_week_date_time_no_millis`
不含毫秒、以 `T` 分隔的基本的基于周的年份日期和时间。 | `"YYYY`W`wwe`T`HHmmssZ"`
"2019W126213446-04:00" +`basic_week_date`
`strict_basic_week_date`
完整的基于周的日期,由四位数的基于周的年份、两位数的年内序数周和一位数的周内序数日组成,以 `W` 分隔。 | `"YYYY`W`wwe"`
`"2019W126"` + +### 完整日期格式 + +完整日期格式的各组成部分中,日期使用 `-` 分隔,时间使用 `:` 分隔。例如 `"2019-03-23T21:34"`。 + +格式名称及描述 | 模式及示例 +:--- | :--- +**日期** | +`date_optional_time`
`strict_date_optional_time`
通用的完整日期和时间。年份必需,月、日和时间可选。时间与日期之间以 `T` 分隔。 | 多种模式。
`"2019--03--23T21:34:46.123456789--04:00"`
`"2019-03-23T21:34:46"`
`"2019-03-23T21:34"`
`"2019"` +`strict_date_optional_time_nanos`
通用的完整日期和时间。年份必需,月、日和时间可选。如果指定了时间,则必须包含小时、分钟和秒,秒的小数部分可选。秒的小数部分为一到九位数,精度为纳秒。时间与日期之间以 `T` 分隔。 | 多种模式。
`"2019-03-23T21:34:46.123456789-04:00"`
`"2019-03-23T21:34:46"`
`"2019"` +`date_time`
`strict_date_time`
以 `T` 分隔的完整日期和时间。 | `"yyyy-MM-dd`T`HH:mm:ss.SSSZ"`
`"2019-03-23T21:34:46.123-04:00"` +`date_time_no_millis`
`strict_date_time_no_millis`
不含毫秒、以 `T` 分隔的完整日期和时间。 | `"yyyy-MM-dd'T'HH:mm:ssZ"`
`"2019-03-23T21:34:46-04:00"` +`date_hour_minute_second_fraction`
`strict_date_hour_minute_second_fraction`
由完整日期、两位数小时、两位数分钟、两位数秒和一到九位数的秒小数部分组成,以 `T` 分隔。 | `"yyyy-MM-dd`T`HH:mm:ss.SSSSSSSSS"`
`"2019-03-23T21:34:46.123456789"`
`"2019-03-23T21:34:46.1"` +`date_hour_minute_second_millis`
`strict_date_hour_minute_second_millis`
由完整日期、两位数小时、两位数分钟、两位数秒和三位数毫秒组成,以 `T` 分隔。 | `"yyyy-MM-dd`T`HH:mm:ss.SSS"`
`"2019-03-23T21:34:46.123"` +`date_hour_minute_second`
`strict_date_hour_minute_second`
由完整日期、两位数小时、两位数分钟和两位数秒组成,以 `T` 分隔。| `"yyyy-MM-dd`T`HH:mm:ss"`
`"2019-03-23T21:34:46"` +`date_hour_minute`
`strict_date_hour_minute`
由完整日期、两位数小时和两位数分钟组成。 | `"yyyy-MM-dd`T`HH:mm"`
`"2019-03-23T21:34"` +`date_hour`
`strict_date_hour`
由完整日期和两位数小时组成,以 `T` 分隔。 | `"yyyy-MM-dd`T`HH"`
`"2019-03-23T21"` +`date`
`strict_date`
由四位数年份、两位数月份和两位数日期组成。 | `"yyyy-MM-dd"`
`"2019-03-23"` +`year_month_day`
`strict_year_month_day`
由四位数年份、两位数月份和两位数日期组成。 | `"yyyy-MM-dd"`
`"2019-03-23"` +`year_month`
`strict_year_month`
由四位数年份和两位数月份组成。 | `"yyyy-MM"`
`"2019-03"` +`year`
`strict_year`
四位数年份。 | `"yyyy"`
`"2019"` +`rfc3339_lenient`
一个兼容 RFC3339 的 DateTimeFormatter,比 `strict_date_optional_time` 等其他宽松的完整日期格式快得多 | `"YYYY"`
`"2019"`
`"YYYY-MM"`
`"2019-03"`
`"YYYY-MM-DD"`
`"2019-03-23"`
`"YYYY-MM-DDThh:mmTZD"`
`"2019-03-23T21:34Z"`
`"YYYY-MM-DDThh:mm:ssTZD"`
`"2019-03-23T21:34:46Z"`
`"YYYY-MM-DDThh:mm:ss.sTZD"`
`"2019-03-23T21:34:46.123456789-04:00"`
`"YYYY-MM-DDThh:mm:ss,sTZD"`
`"2019-03-23T21:34:46,123456789-04:00"` +**时间** | +`time`
`strict_time`
由两位数小时、两位数分钟、两位数秒、一到九位数的秒小数部分和时区偏移组成。 | `"HH:mm:ss.SSSSSSSSSZ"`
`"21:34:46.123456789-04:00"`
`"21:34:46.1-04:00"` +`time_no_millis`
`strict_time_no_millis`
由两位数小时、两位数分钟、两位数秒和时区偏移组成。 | `"HH:mm:ssZ"`
`"21:34:46-04:00"` +`hour_minute_second_fraction`
`strict_hour_minute_second_fraction`
由两位数小时、两位数分钟、两位数秒和一到九位数的秒小数部分组成。 | `"HH:mm:ss.SSSSSSSSS"`
`"21:34:46.1"`
`"21:34:46.123456789"` +`hour_minute_second_millis`
`strict_hour_minute_second_millis`
由两位数小时、两位数分钟、两位数秒和三位数毫秒组成。 | `"HH:mm:ss.SSS"`
`"21:34:46.123"` +`hour_minute_second`
`strict_hour_minute_second`
由两位数小时、两位数分钟和两位数秒组成。 | `"HH:mm:ss"`
`"21:34:46"` +`hour_minute`
`strict_hour_minute`
由两位数小时和两位数分钟组成。 | `"HH:mm"`
`"21:34"` +`hour`
`strict_hour`
两位数小时。 | `"HH"`
`"21"` +**T 时间** | +`t_time`
`strict_t_time`
由两位数小时、两位数分钟、两位数秒、一到九位数的秒小数部分和时区偏移组成,以 `T` 开头。 | `"`T`HH:mm:ss.SSSSSSSSSZ"
"T21:34:46.123456789-04:00"`
`"T21:34:46.1-04:00"` +`t_time_no_millis`
`strict_t_time_no_millis`
由两位数小时、两位数分钟、两位数秒和时区偏移组成,以 `T` 开头。 | `"`T`HH:mm:ssZ"`
`"T21:34:46-04:00"` +**序数日期** | +`ordinal_date_time`
`strict_ordinal_date_time`
以 `T` 分隔的完整序数日期和时间。 | `"yyyy-DDD`T`HH:mm:ss.SSSZ"`
`"2019-082T21:34:46.123-04:00"` +`ordinal_date_time_no_millis`
`strict_ordinal_date_time_no_millis`
不含毫秒、以 `T` 分隔的完整序数日期和时间。 | `"yyyy-DDD`T`HH:mm:ssZ"`
`"2019-082T21:34:46-04:00"` +`ordinal_date`
`strict_ordinal_date`
由四位数年份和三位数的年内序数日组成的完整序数日期。 | `"yyyy-DDD"`
`"2019-082"` +**基于周的日期** | +`week_date_time`
`strict_week_date_time`
以 `T` 分隔的完整的基于周的日期和时间。周日期由四位数的基于周的年份、两位数的年内序数周和一位数的周内序数日组成。时间由两位数小时、两位数分钟、两位数秒、一到九位数的秒小数部分和时区偏移组成。 | `"YYYY-`W`ww-e`T`HH:mm:ss.SSSSSSSSSZ"`
`"2019-W12-6T21:34:46.1-04:00"`
`"2019-W12-6T21:34:46.123456789-04:00"` +`week_date_time_no_millis`
`strict_week_date_time_no_millis`
不含毫秒、以 `T` 分隔的完整的基于周的日期和时间。周日期由四位数的基于周的年份、两位数的年内序数周和一位数的周内序数日组成。时间由两位数小时、两位数分钟、两位数秒和时区偏移组成。 | `"YYYY-`W`ww-e`T`HH:mm:ssZ"`
`"2019-W12-6T21:34:46-04:00"` +`week_date`
`strict_week_date`
完整的基于周的日期,由四位数的基于周的年份、两位数的年内序数周和一位数的周内序数日组成。 | `"YYYY-`W`ww-e"`
`"2019-W12-6"` +`weekyear_week_day`
`strict_weekyear_week_day`
由四位数的基于周的年份、两位数的年内序数周和一位数的周内日组成。 | `"YYYY-'W'ww-e"`
`"2019-W12-6"` +`weekyear_week`
`strict_weekyear_week`
由四位数的基于周的年份和两位数的年内序数周组成。 | `"YYYY-`W`ww"`
`"2019-W12"` +`weekyear`
`strict_weekyear`
四位数的基于周的年份。 | `"YYYY"`
`"2019"` + +## 自定义格式 + +可以为日期字段创建自定义格式。例如,以下请求以常见的 `"MM/dd/yyyy"` 格式指定日期: + +```json +PUT testindex +{ + "mappings" : { + "properties" : { + "release_date" : { + "type" : "date", + "format" : "MM/dd/yyyy" + } + } + } +} +``` + +索引一个包含日期的文档(Document): + +```json +PUT testindex/_doc/21 +{ + "release_date" : "03/21/2019" +} +``` + +搜索精确日期时,需以相同格式提供该日期: + +```json +GET testindex/_search +{ + "query" : { + "match": { + "release_date" : { + "query": "03/21/2019" + } + } + } +} +``` + +范围查询默认使用字段映射中的格式。也可以通过提供 `format` 参数,以不同的格式指定日期范围: + +```json +GET testindex/_search +{ + "query": { + "range": { + "release_date": { + "gte": "2019-01-01", + "lte": "2019-12-31", + "format": "yyyy-MM-dd" + } + } + } +} +``` + +## 日期计算 + +日期字段类型支持在查询(Query)中使用日期计算(date math)来指定时间段。例如,[range 查询](/query-dsl/term/range)中的 `gt`、`gte`、`lt` 和 `lte` 参数,以及[日期范围聚合](/aggregations/bucket/date-range)中的 `from` 和 `to` 参数,都接受日期计算表达式。 + +日期计算表达式包含一个固定日期,后面可以跟一个或多个数学表达式。固定日期可以是 `now`(当前日期和时间,以自纪元以来的毫秒数表示),也可以是以 `||` 结尾的日期字符串(例如 `2022-05-18||`)。该日期必须采用[默认格式](#default-format)(默认为 `strict_date_time_no_millis||strict_date_optional_time||epoch_millis`)。 + +::: info 注意 +如果在字段映射中指定了多个日期格式,OpenSearch 会使用第一个格式将自纪元以来的毫秒值转换为字符串。
+如果字段映射中没有指定格式,OpenSearch 会使用 `strict_date_optional_time` 格式将纪元值转换为字符串。 +::: + +日期计算支持以下数学运算符。 + +运算符 | 描述 | 示例 +:--- | :--- | :--- +`+` | 加法 | `+1M`:加 1 个月。 +`-` | 减法 | `-1y`:减 1 年。 +`/` | 向下取整 | `/h`:取整到该小时的开始。 + +日期计算支持以下时间单位: + +::: info 注意 +`y`:年
+`M`:月
+`w`:周
+`d`:天
+`h` 或 `H`:小时
+`m`:分钟
+`s`:秒 +::: + +### 表达式示例 + +以下示例表达式演示了日期计算的用法: + +- `now+1M`:当前日期和时间(以自纪元以来的毫秒数表示)加 1 个月。 +- `2022-05-18||/M`:`05/18/2022`,取整到该月的开始。解析结果为 `2022-05-01`。 +- `2022-05-18T15:23||/h`:`05/18/2022` 的 `15:23`,取整到该小时的开始。解析结果为 `2022-05-18T15`。 +- `2022-05-18T15:23:17.789||+2M-1d/d`:`05/18/2022` 的 `15:23:17.789` 加 2 个月再减 1 天,取整到当天的开始。解析结果为 `2022-07-17`。 + +### 在 range 查询中使用日期计算 + +以下示例演示了如何在 [range 查询](/query-dsl/term/range)中使用日期计算。 + +创建一个索引,将 `release_date` 映射为 `date`: + +```json +PUT testindex +{ + "mappings" : { + "properties" : { + "release_date" : { + "type" : "date" + } + } + } +} +``` + +向该索引中索引两个文档: + +```json +PUT testindex/_doc/1 +{ + "release_date": "2022-09-14" +} +``` + +```json +PUT testindex/_doc/2 +{ + "release_date": "2022-11-15" +} +``` + +以下查询搜索 `release_date` 在 `09/14/2022` 之后 2 个月零 1 天之内的文档。范围的下限会取整到 `09/14/2022` 当天的开始: + +```json +GET testindex/_search +{ + "query": { + "range": { + "release_date": { + "gte": "2022-09-14T15:23||/d", + "lte": "2022-09-14||+2M+1d" + } + } + } +} +``` + +响应包含这两个文档: + +```json +{ + "took" : 1, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 2, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "testindex", + "_id" : "2", + "_score" : 1.0, + "_source" : { + "release_date" : "2022-11-14" + } + }, + { + "_index" : "testindex", + "_id" : "1", + "_score" : 1.0, + "_source" : { + "release_date" : "2022-09-14" + } + } + ] + } +} +``` diff --git a/i18n/zh/field-types/supported-field-types/dates.md b/i18n/zh/field-types/supported-field-types/dates.md new file mode 100644 index 00000000..ceb622f8 --- /dev/null +++ b/i18n/zh/field-types/supported-field-types/dates.md @@ -0,0 +1,12 @@ +--- +title: 日期字段类型 +--- + +# 日期字段类型 + +日期字段类型(Date Field Type)包含一个日期值,该值可以使用不同的日期格式进行格式化。下表列出了 OpenSearch 支持的所有日期字段类型。 + +字段数据类型 | 描述 +:--- | :--- +[`date`](/field-types/supported-field-types/date) | 以毫秒精度存储的日期。 +[`date_nanos`](/field-types/supported-field-types/date-nanos) | 以纳秒精度存储的日期。 diff --git a/i18n/zh/field-types/supported-field-types/flat-object.md b/i18n/zh/field-types/supported-field-types/flat-object.md new file mode 100644 index 00000000..fb10bbc6 --- /dev/null +++ b/i18n/zh/field-types/supported-field-types/flat-object.md @@ -0,0 +1,234 @@ +--- +title: 扁平对象 +--- + +# 扁平对象字段类型 + +在 OpenSearch 中,索引文档(Document)之前不必先指定映射(Mapping)。如果没有指定映射,OpenSearch 会使用[动态映射](/field-types/#dynamic-mapping)自动映射文档中的每个字段及其子字段。在摄取日志之类的文档时,可能无法事先知道每个字段的子字段名称和类型。在这种情况下,动态映射所有新的子字段很快就会导致“映射爆炸”,不断增长的字段数量可能会降低集群(Cluster)的性能。 + +扁平对象(flat object)字段类型通过将整个 JSON 对象视为字符串来解决这个问题。JSON 对象中的子字段可以使用标准的点路径表示法访问,但不会为了快速查找而被索引。 + +::: info 注意 +点表示法中字段值的最大长度为 224 − 1。 +::: + +扁平对象字段类型具有以下优点: + +- 读取高效:获取性能与 keyword 字段相近。 +- 内存高效:将整个复杂的 JSON 对象存储在一个字段中,而不索引其所有子字段,可以减少索引中的字段数量。 +- 空间高效:OpenSearch 不会为扁平对象中的子字段创建倒排索引,从而节省空间。 +- 迁移兼容性:可以将数据从支持类似扁平类型的系统迁移到 OpenSearch。 + +由于子字段不会被索引,当一个字段及其子字段主要用于读取、而不用作搜索条件时,适合将该字段映射为扁平对象。扁平对象适用于包含大量字段的对象,或者无法事先知道键名的情况。 + +扁平对象支持使用或不使用点路径表示法的精确匹配查询(Query)。有关支持的查询类型的完整列表,请参阅[支持的查询](#supported-queries)。 + +::: info 注意 +在文档中搜索嵌套字段的特定值可能效率较低,因为这可能需要对索引进行全量扫描,而这是一项开销很大的操作。 +::: + +扁平对象不支持: + +- 特定类型的解析。 +- 数值运算,例如数值比较或数值排序。 +- 文本分析。 +- 高亮显示。 +- 使用点表示法对子字段进行聚合(Aggregation)。 +- 按子字段过滤。 + +## 支持的查询 + +扁平对象字段类型支持以下查询: + +- [Term](/query-dsl/term/term) +- [Terms](/query-dsl/term/terms) +- [Terms set](/query-dsl/term/terms-set) +- [Prefix](/query-dsl/term/prefix) +- [Range](/query-dsl/term/range) +- [Match](/query-dsl/full-text/match) +- [Multi-match](/query-dsl/full-text/multi-match) +- [Query string](/query-dsl/full-text/query-string) +- [Simple query string](/query-dsl/full-text/simple-query-string) +- [Exists](/query-dsl/term/exists) + +## 限制 + +在 OpenSearch 2.7 中,扁平对象存在以下限制: + +- 扁平对象不支持开放参数。 +- 不支持使用 Painless 脚本和通配符查询来检索子字段的值。 + +这些功能计划在未来的版本中提供。 + +## 使用扁平对象 + +以下示例演示了如何将字段映射为扁平对象、索引包含扁平对象字段的文档,以及在这些文档中搜索扁平对象的叶子值。 + +首先,为索引创建一个映射,其中 `issue` 的类型为 `flat_object`: + +```json +PUT /test-index/ +{ + "mappings": { + "properties": { + "issue": { + "type": "flat_object" + } + } + } +} +``` + +接着,索引两个包含扁平对象字段的文档: + +```json +PUT /test-index/_doc/1 +{ + "issue": { + "number": "123456", + "labels": { + "version": "2.1", + "backport": [ + "2.0", + "1.3" + ], + "category": { + "type": "API", + "level": "enhancement" + } + } + } +} +``` + +```json +PUT /test-index/_doc/2 +{ + "issue": { + "number": "123457", + "labels": { + "version": "2.2", + "category": { + "type": "API", + "level": "bug" + } + } + } +} +``` + +如需搜索扁平对象的叶子值,可以使用 GET 或 POST 请求。即使不知道字段名称,也可以在整个扁平对象中搜索叶子值。例如,以下请求搜索所有标记为 bug 的问题: + +```json +GET /test-index/_search +{ + "query": { + "match": {"issue": "bug"} + } +} +``` + +或者,如果知道要搜索的子字段名称,可以用点表示法提供该字段的路径: + +```json +GET /test-index/_search +{ + "query": { + "match": {"issue.labels.category.level": "bug"} + } +} +``` + +在这两种情况下,响应都相同,且包含文档 2: + +```json +{ + "took": 1, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.0303539, + "hits": [ + { + "_index": "test-index", + "_id": "2", + "_score": 1.0303539, + "_source": { + "issue": { + "number": "123457", + "labels": { + "version": "2.2", + "category": { + "type": "API", + "level": "bug" + } + } + } + } + } + ] + } +} +``` + +使用 prefix 查询,可以搜索版本号以 `2.` 开头的所有问题: + +```json +GET /test-index/_search +{ + "query": { + "prefix": {"issue.labels.version": "2."} + } +} +``` + +使用 range 查询,可以搜索版本 2.0 到 2.1 的所有问题: + +```json +GET /test-index/_search +{ + "query": { + "range": { + "issue": { + "gte": "2.0", + "lte": "2.1" + } + } + } +} +``` + +## 将子字段定义为扁平对象 + +可以将 JSON 对象的某个子字段定义为扁平对象。例如,使用以下查询将 `issue.labels` 定义为 `flat_object`: + +```json +PUT /test-index/ +{ + "mappings": { + "properties": { + "issue": { + "properties": { + "number": { + "type": "double" + }, + "labels": { + "type": "flat_object" + } + } + } + } + } +} +``` + +由于 `issue.number` 不属于扁平对象,因此可以用它来聚合和排序文档。 diff --git a/i18n/zh/field-types/supported-field-types/geo-point.md b/i18n/zh/field-types/supported-field-types/geo-point.md new file mode 100644 index 00000000..86571671 --- /dev/null +++ b/i18n/zh/field-types/supported-field-types/geo-point.md @@ -0,0 +1,98 @@ +--- +title: 地理点 +--- + +# 地理点字段类型 + +地理点(geopoint)字段类型包含一个由纬度和经度指定的地理点。 + +## 示例 + +创建一个包含地理点字段类型的映射(Mapping): + +```json +PUT testindex1 +{ + "mappings": { + "properties": { + "point": { + "type": "geo_point" + } + } + } +} +``` + +## 格式 + +地理点可以按以下格式进行索引: + +- 包含纬度和经度的对象 + +```json +PUT testindex1/_doc/1 +{ + "point": { + "lat": 40.71, + "lon": 74.00 + } +} +``` + +- "`latitude`,`longitude`" 格式的字符串 + +```json +PUT testindex1/_doc/2 +{ + "point": "40.71,74.00" +} +``` + +- geohash + +```json +PUT testindex1/_doc/3 +{ + "point": "txhxegj0uyp3" +} +``` + +- [`longitude`, `latitude`] 格式的数组 + +```json +PUT testindex1/_doc/4 +{ + "point": [74.00, 40.71] +} +``` + +- "POINT(`longitude` `latitude`)" 格式的 [Well-Known Text](https://docs.opengeospatial.org/is/12-063r5/12-063r5.html) POINT + +```json +PUT testindex1/_doc/5 +{ + "point": "POINT (74.00 40.71)" +} +``` + +- GeoJSON 格式,其中 `coordinates` 采用 [`longitude`, `latitude`] 格式 + +```json +PUT testindex1/_doc/6 +{ + "point": { + "type": "Point", + "coordinates": [74.00, 40.71] + } +} +``` + +## 参数 + +下表列出了地理点字段类型接受的参数。所有参数均为可选。 + +参数 | 描述 +:--- | :--- +`ignore_malformed` | 一个布尔值,指定忽略格式错误的值而不抛出异常。纬度的有效值范围为 [-90, 90],经度的有效值范围为 [-180, 180]。默认值为 `false`。 +`ignore_z_value` | 仅适用于具有三个坐标的点。如果 `ignore_z_value` 为 `true`,则第三个坐标不会被索引,但仍会存储在 _source 字段中。如果 `ignore_z_value` 为 `false`,则会抛出异常。 +[`null_value`](/field-types/supported-field-types/#null-value) | 用于替代 `null` 的值,必须与字段类型相同。如果未指定此参数,当字段值为 `null` 时,该字段会被视为缺失。默认值为 `null`。 diff --git a/i18n/zh/field-types/supported-field-types/geo-shape.md b/i18n/zh/field-types/supported-field-types/geo-shape.md new file mode 100644 index 00000000..3dd07bfe --- /dev/null +++ b/i18n/zh/field-types/supported-field-types/geo-shape.md @@ -0,0 +1,378 @@ +--- +title: 地理形状 +--- + +# 地理形状字段类型 + +地理形状(geoshape)字段类型包含一个地理形状,例如多边形或地理点的集合。为了索引地理形状,OpenSearch 会将形状细分为三角形网格,并将每个三角形存储在 BKD 树中。这可以提供 10-7 十进制度的精度,代表近乎完美的空间分辨率。该过程的性能主要受所索引多边形的顶点数量影响。 + +## 示例 + +创建一个包含地理形状字段类型的映射(Mapping): + +```json +PUT testindex +{ + "mappings": { + "properties": { + "location": { + "type": "geo_shape" + } + } + } +} +``` + +## 格式 + +地理形状可以按以下格式进行索引: + +- [GeoJSON](https://geojson.org/) +- [Well-Known Text(WKT)](https://docs.opengeospatial.org/is/12-063r5/12-063r5.html) + +::: info 注意 +在 GeoJSON 和 WKT 中,坐标数组内的坐标都必须按 `longitude, latitude` 的顺序指定。请注意,在这种格式中经度在前。 +::: + +## 地理形状类型 + +下表描述了可用的地理形状类型及其与 GeoJSON 和 WKT 类型的对应关系。 + +OpenSearch 类型 | GeoJSON 类型 | WKT 类型 | 描述 +:--- | :--- | :--- | :--- +[`point`](#point) | Point | POINT | 由纬度和经度指定的地理点。OpenSearch 使用世界大地坐标系(WGS84)坐标。 +[`linestring`](#linestring) | LineString | LINESTRING | 由两个或更多点指定的线。可以是一条直线,也可以是由相连线段组成的路径。 +[`polygon`](#polygon) | Polygon | POLYGON | 由坐标形式的顶点列表指定的多边形。多边形必须是闭合的,即最后一个点必须与第一个点相同。因此,要创建一个 n 边形,需要 n+1 个顶点。顶点的最小数量为四个,此时创建的是一个三角形。 +[`multipoint`](#multipoint) | MultiPoint | MULTIPOINT | 一组互不相连但彼此相关的离散点组成的数组。 +[`multilinestring`](#multilinestring) | MultiLineString | MULTILINESTRING | 由线串组成的数组。 +[`multipolygon`](#multipolygon) | MultiPolygon | MULTIPOLYGON | 由多边形组成的数组。 +[`geometrycollection`](#geometry-collection) | GeometryCollection | GEOMETRYCOLLECTION | 地理形状的集合,其中的形状可以是不同类型。 +[`envelope`](#envelope) | N/A | BBOX | 由左上角和右下角顶点指定的边界矩形。 + +## 点 + +点是由纬度和经度指定的一对坐标。 + +以 GeoJSON 格式索引一个点: + +```json +PUT testindex/_doc/1 +{ + "location" : { + "type" : "point", + "coordinates" : [74.00, 40.71] + } +} +``` + +以 WKT 格式索引一个点: + +```json +PUT testindex/_doc/1 +{ + "location" : "POINT (74.0060 40.7128)" +} +``` + +## 线串 + +线串(linestring)是由两个或更多点指定的线。如果这些点共线,则线串是一条直线;否则,线串表示由线段组成的路径。 + +以 GeoJSON 格式索引一个线串: + +```json +PUT testindex/_doc/2 +{ + "location" : { + "type" : "linestring", + "coordinates" : [[74.0060, 40.7128], [71.0589, 42.3601]] + } +} +``` + +以 WKT 格式索引一个线串: + +```json +PUT testindex/_doc/2 +{ + "location" : "LINESTRING (74.0060 40.7128, 71.0589 42.3601)" +} +``` + +## 多边形 + +多边形由坐标形式的顶点列表指定。多边形必须是闭合的,即最后一个点必须与第一个点相同。以下示例使用四个点创建一个三角形。 + +::: info 注意 +GeoJSON 要求按逆时针顺序列出多边形的顶点。WKT 对顶点顺序没有特定要求。 +::: + +以 GeoJSON 格式索引一个多边形(三角形): + +```json +PUT testindex/_doc/3 +{ + "location" : { + "type" : "polygon", + "coordinates" : [ + [[74.0060, 40.7128], + [71.0589, 42.3601], + [73.7562, 42.6526], + [74.0060, 40.7128]] + ] + } +} +``` + +以 WKT 格式索引一个多边形(三角形): + +```json +PUT testindex/_doc/3 +{ + "location" : "POLYGON ((74.0060 40.7128, 71.0589 42.3601, 73.7562 42.6526, 74.0060 40.7128))" +} +``` + +多边形内部可以有孔。在这种情况下,`coordinates` 字段将包含多个数组。第一个数组表示外部多边形,后续的每个数组表示一个孔。孔用多边形表示,并以坐标数组的形式指定。 + +::: info 注意 +GeoJSON 要求按逆时针顺序列出多边形的顶点,按顺时针顺序列出孔的顶点。WKT 对顶点顺序没有特定要求。 +::: + +以 GeoJSON 格式索引一个带有三角形孔的多边形(三角形): + +```json +PUT testindex/_doc/4 +{ + "location" : { + "type" : "polygon", + "coordinates" : [ + [[74.0060, 40.7128], + [71.0589, 42.3601], + [73.7562, 42.6526], + [74.0060, 40.7128]], + + [[72.6734,41.7658], + [72.6506, 41.5623], + [73.0515, 41.5582], + [72.6734, 41.7658]] + ] + } +} +``` + +以 WKT 格式索引一个带有三角形孔的多边形(三角形): + +```json +PUT testindex/_doc/4 +{ + "location" : "POLYGON ((40.7128 74.0060, 42.3601 71.0589, 42.6526 73.7562, 40.7128 74.0060), (41.7658 72.6734, 41.5623 72.6506, 41.5582 73.0515, 41.7658 72.6734))" +} +``` + +在 OpenSearch 中,可以按顺时针或逆时针顺序列出顶点来指定多边形。对于不跨越日期变更线(宽度小于 180°)的多边形,这种方式没有问题。但是,跨越日期变更线(宽度大于 180°)的多边形可能存在歧义,因为 WKT 对顶点顺序没有特定要求。因此,对于跨越日期变更线的多边形,必须按逆时针顺序列出其顶点。 + +可以在映射时定义 [`orientation`](#parameters) 参数来指定顶点的遍历顺序: + +```json +PUT testindex +{ + "mappings": { + "properties": { + "location": { + "type": "geo_shape", + "orientation" : "left" + } + } + } +} +``` + +之后索引的文档(Document)可以覆盖 `orientation` 设置: + +```json +PUT testindex/_doc/3 +{ + "location" : { + "type" : "polygon", + "orientation" : "cw", + "coordinates" : [ + [[74.0060, 40.7128], + [71.0589, 42.3601], + [73.7562, 42.6526], + [74.0060, 40.7128]] + ] + } +} +``` + +## 多点 + +多点(multipoint)是一组互不相连但彼此相关的离散点组成的数组。 + +以 GeoJSON 格式索引一个多点: + +```json +PUT testindex/_doc/6 +{ + "location" : { + "type" : "multipoint", + "coordinates" : [ + [74.0060, 40.7128], + [71.0589, 42.3601] + ] + } +} +``` + +以 WKT 格式索引一个多点: + +```json +PUT testindex/_doc/6 +{ + "location" : "MULTIPOINT (74.0060 40.7128, 71.0589 42.3601)" +} +``` + +## 多线串 + +多线串(multilinestring)是由线串组成的数组。 + +以 GeoJSON 格式索引一个线串: + +```json +PUT testindex/_doc/2 +{ + "location" : { + "type" : "multilinestring", + "coordinates" : [ + [[74.0060, 40.7128], [71.0589, 42.3601]], + [[73.7562, 42.6526], [72.6734, 41.7658]] + ] + } +} +``` + +以 WKT 格式索引一个线串: + +```json +PUT testindex/_doc/2 +{ + "location" : "MULTILINESTRING ((74.0060 40.7128, 71.0589 42.3601), (73.7562 42.6526, 72.6734 41.7658))" +} +``` + +## 多多边形 + +多多边形(multipolygon)是由多边形组成的数组。在此示例中,第一个多边形包含一个孔,第二个多边形不包含孔。 + +以 GeoJSON 格式索引一个多多边形: + +```json +PUT testindex/_doc/4 +{ + "location" : { + "type" : "multipolygon", + "coordinates" : [ + [ + [[74.0060, 40.7128], + [71.0589, 42.3601], + [73.7562, 42.6526], + [74.0060, 40.7128]], + + [[72.6734,41.7658], + [72.6506, 41.5623], + [73.0515, 41.5582], + [72.6734, 41.7658]] + ], + [ + [[73.9776, 40.7614], + [73.9554, 40.7827], + [73.9631, 40.7812], + [73.9776, 40.7614]] + ] + ] + } +} +``` + +以 WKT 格式索引一个多多边形: + +```json +PUT testindex/_doc/4 +{ + "location" : "MULTIPOLYGON (((40.7128 74.0060, 42.3601 71.0589, 42.6526 73.7562, 40.7128 74.0060), (41.7658 72.6734, 41.5623 72.6506, 41.5582 73.0515, 41.7658 72.6734)), ((73.9776 40.7614, 73.9554 40.7827, 73.9631 40.7812, 73.9776 40.7614)))" +} +``` + +## 几何集合 + +几何集合(geometry collection)是地理形状的集合,其中的形状可以是不同类型。 + +以 GeoJSON 格式索引一个几何集合: + +```json +PUT testindex/_doc/7 +{ + "location" : { + "type": "geometrycollection", + "geometries": [ + { + "type": "point", + "coordinates": [74.0060, 40.7128] + }, + { + "type": "linestring", + "coordinates": [[73.7562, 42.6526], [72.6734, 41.7658]] + } + ] + } +} +``` + +以 WKT 格式索引一个几何集合: + +```json +PUT testindex/_doc/7 +{ + "location" : "GEOMETRYCOLLECTION (POINT (74.0060 40.7128), LINESTRING(73.7562 42.6526, 72.6734 41.7658))" +} +``` + +## 包络 + +包络(envelope)是由左上角和右下角顶点指定的边界矩形。GeoJSON 格式为 `[[minLon, maxLat], [maxLon, minLat]]`。 + +以 GeoJSON 格式索引一个包络: + +```json +PUT testindex/_doc/2 +{ + "location" : { + "type" : "envelope", + "coordinates" : [[71.0589, 42.3601], [74.0060, 40.7128]] + } +} +``` + +在 WKT 格式中,使用 `BBOX (minLon, maxLon, maxLat, minLat)`。 + +以 WKT BBOX 格式索引一个包络: + +```json +PUT testindex/_doc/8 +{ + "location" : "BBOX (71.0589, 74.0060, 42.3601, 40.7128)" +} +``` + +## 参数 + +下表列出了地理形状字段类型接受的参数。所有参数均为可选。 + +参数 | 描述 +:--- | :--- +`coerce` | 一个布尔值,指定是否自动闭合未闭合的线性环。默认值为 `false`。 +`ignore_malformed` | 一个布尔值,指定忽略格式错误的 GeoJSON 或 WKT 地理形状而不抛出异常。默认值为 `false`(地理形状格式错误时抛出异常)。 +`ignore_z_value` | 仅适用于具有三个坐标的点。如果 `ignore_z_value` 为 `true`,则第三个坐标不会被索引,但仍会存储在 _source 字段中。如果 `ignore_z_value` 为 `false`,则会抛出异常。默认值为 `true`。 +`orientation` | 指定地理形状坐标列表中顶点的遍历顺序。`orientation` 可取以下值:
1. RIGHT:逆时针。使用以下任一字符串(大写或小写)指定 RIGHT 方向:`right`、`counterclockwise`、`ccw`。
2. LEFT:顺时针。使用以下任一字符串(大写或小写)指定 LEFT 方向:`left`、`clockwise`、`cw`。该值可以被单个文档覆盖。
默认值为 `RIGHT`。 diff --git a/i18n/zh/field-types/supported-field-types/geographic.md b/i18n/zh/field-types/supported-field-types/geographic.md new file mode 100644 index 00000000..45a69142 --- /dev/null +++ b/i18n/zh/field-types/supported-field-types/geographic.md @@ -0,0 +1,12 @@ +--- +title: 地理字段类型 +--- + +# 地理字段类型 + +地理字段(Geographic Field)包含表示地图上的点或形状的值。下表列出了 OpenSearch 支持的所有地理字段类型。 + +字段数据类型 | 描述 +:--- | :--- +[`geo_point`](/field-types/supported-field-types/geo-point) | 由纬度和经度指定的地理点。 +[`geo_shape`](/field-types/supported-field-types/geo-shape) | 地理形状,例如多边形或地理点的集合。 diff --git a/i18n/zh/field-types/supported-field-types/index.md b/i18n/zh/field-types/supported-field-types/index.md new file mode 100644 index 00000000..19040468 --- /dev/null +++ b/i18n/zh/field-types/supported-field-types/index.md @@ -0,0 +1,185 @@ +--- +title: 支持的字段类型 +--- + +# 支持的字段类型 + +创建映射(Mapping)时,可以为字段指定数据类型。下表列出了 OpenSearch 支持的所有数据字段类型(Field Type)。 + +类别 | 字段类型及描述 +:--- | :--- +别名 | [`alias`](/field-types/supported-field-types/alias):现有字段的附加名称。 +二进制 | [`binary`](/field-types/supported-field-types/binary):Base64 编码的二进制值。 +[数值](/field-types/supported-field-types/numeric) | 数值(`byte`、`double`、`float`、`half_float`、`integer`、`long`、[`unsigned_long`](/field-types/supported-field-types/unsigned-long)、`scaled_float`、`short`)。 +布尔 | [`boolean`](/field-types/supported-field-types/boolean):布尔值。 +[日期](/field-types/supported-field-types/dates)| [`date`](/field-types/supported-field-types/date):以毫秒存储的日期。
[`date_nanos`](/field-types/supported-field-types/date-nanos):以纳秒存储的日期。 +IP | [`ip`](/field-types/supported-field-types/ip):IPv4 或 IPv6 格式的 IP 地址。 +[范围](/field-types/supported-field-types/range) | 值的范围(`integer_range`、`long_range`、`double_range`、`float_range`、`date_range`、`ip_range`)。 +[对象](/field-types/supported-field-types/object-fields)| [`object`](/field-types/supported-field-types/object):JSON 对象。
[`nested`](/field-types/supported-field-types/nested):当数组中的对象需要作为单独的文档独立索引时使用。
[`flat_object`](/field-types/supported-field-types/flat-object):被视为字符串的 JSON 对象。
[`join`](/field-types/supported-field-types/join):在同一索引中的文档之间建立父子关系。 +[字符串](/field-types/supported-field-types/string)|[`keyword`](/field-types/supported-field-types/keyword):包含不经过分析的字符串。
[`text`](/field-types/supported-field-types/text):包含经过分析的字符串。
[`match_only_text`](/field-types/supported-field-types/match-only-text):`text` 字段的空间优化版本。
[`token_count`](/field-types/supported-field-types/token-count):存储字符串中经分析后的词元(Token)数量。 +[自动补全](/field-types/supported-field-types/autocomplete) |[`completion`](/field-types/supported-field-types/completion):通过补全建议器(completion suggester)提供自动补全功能。
[`search_as_you_type`](/field-types/supported-field-types/search-as-you-type):同时使用前缀补全和中缀补全,提供边输入边搜索功能。 +[地理](/field-types/supported-field-types/geographic)| [`geo_point`](/field-types/supported-field-types/geo-point):地理点。
[`geo_shape`](/field-types/supported-field-types/geo-shape):地理形状。 +[排名](/field-types/supported-field-types/rank) | 提高或降低文档的相关性评分(Relevance Score)(`rank_feature`、`rank_features`)。 +k-NN 向量 | [`knn_vector`](/field-types/supported-field-types/knn-vector):允许将 k-NN 向量索引到 OpenSearch 中,并执行各种 k-NN 搜索。 +Percolator | [`percolator`](/field-types/supported-field-types/percolator):指定将该字段视为查询(Query)。 + +## 数组 + +OpenSearch 中没有专门的数组字段类型。不过,可以向任何字段传入一个值数组。数组中的所有值必须具有相同的字段类型。 + +```json +PUT testindex1/_doc/1 +{ + "number": 1 +} + +PUT testindex1/_doc/2 +{ + "number": [1, 2, 3] +} +``` + +## 多字段 + +多字段(Multifield)用于以不同方式索引同一个字段。字符串通常会被映射为 `text` 用于全文查询(Full-text Query),同时映射为 `keyword` 用于精确值查询。 + +可以使用 `fields` 参数创建多字段。例如,可以将图书的 `title` 映射为 `text` 类型,同时保留一个 `keyword` 类型的 `title.raw` 子字段。 + +```json +PUT books +{ + "mappings" : { + "properties" : { + "title" : { + "type" : "text", + "fields" : { + "raw" : { + "type" : "keyword" + } + } + } + } + } +} +``` + +## Null 值 + +将字段的值设置为 `null`、空数组或由 `null` 值组成的数组,等同于该字段为空。因此,无法搜索该字段为 `null` 的文档(Document)。 + +如需让字段的 `null` 值可被搜索,可以在索引的映射中指定该字段的 `null_value` 参数。这样,传入该字段的所有 `null` 值都会被替换为指定的 `null_value`。 + +::: info 注意 +`null_value` 参数必须与字段类型相同。例如,如果字段是字符串,那么该字段的 `null_value` 也必须是字符串。 +::: + +### 示例 + +创建一个映射,将 `emergency_phone` 字段中的 `null` 值替换为字符串 "NONE": + +```json +PUT testindex +{ + "mappings": { + "properties": { + "name": { + "type": "keyword" + }, + "emergency_phone": { + "type": "keyword", + "null_value": "NONE" + } + } + } +} +``` + +向 testindex 索引三个文档。文档 1 和文档 3 的 `emergency_phone` 字段包含 `null`,而文档 2 的 `emergency_phone` 字段是一个空数组: + +```json +PUT testindex/_doc/1 +{ + "name": "Akua Mansa", + "emergency_phone": null +} +``` + +```json +PUT testindex/_doc/2 +{ + "name": "Diego Ramirez", + "emergency_phone" : [] +} +``` + +```json +PUT testindex/_doc/3 +{ + "name": "Jane Doe", + "emergency_phone": [null, null] +} +``` + +搜索没有紧急联系电话的人员: + +```json +GET testindex/_search +{ + "query": { + "term": { + "emergency_phone": "NONE" + } + } +} +``` + +响应包含文档 1 和文档 3,但不包含文档 2,因为只有显式的 `null` 值才会被替换为字符串 "NONE": + +```json +{ + "took" : 1, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 2, + "relation" : "eq" + }, + "max_score" : 0.18232156, + "hits" : [ + { + "_index" : "testindex", + "_type" : "_doc", + "_id" : "1", + "_score" : 0.18232156, + "_source" : { + "name" : "Akua Mansa", + "emergency_phone" : null + } + }, + { + "_index" : "testindex", + "_type" : "_doc", + "_id" : "3", + "_score" : 0.18232156, + "_source" : { + "name" : "Jane Doe", + "emergency_phone" : [ + null, + null + ] + } + } + ] + } +} +``` + +::: info 注意 +`_source` 字段仍然包含显式的 `null` 值,因为它不受 `null_value` 的影响。 +::: diff --git a/i18n/zh/field-types/supported-field-types/ip.md b/i18n/zh/field-types/supported-field-types/ip.md new file mode 100644 index 00000000..47f7724e --- /dev/null +++ b/i18n/zh/field-types/supported-field-types/ip.md @@ -0,0 +1,106 @@ +--- +title: IP 地址 +--- + +# IP 地址字段类型 + +ip 字段类型包含 IPv4 或 IPv6 格式的 IP 地址。 + +::: info 注意 +如需表示 IP 地址范围,可以使用 IP [范围字段类型](/field-types/supported-field-types/range)。 +::: + +## 示例 + +创建一个包含 IP 地址的映射(Mapping): + +```json +PUT testindex +{ + "mappings" : { + "properties" : { + "ip_address" : { + "type" : "ip" + } + } + } +} +``` + +索引一个包含 IP 地址的文档(Document): + +```json +PUT testindex/_doc/1 +{ + "ip_address" : "10.24.34.0" +} +``` + +在索引中查询特定的 IP 地址: + +```json +GET testindex/_doc/1 +{ + "query": { + "term": { + "ip_address": "10.24.34.0" + } + } +} +``` + +## 搜索 IP 地址及其关联的网络掩码 + +可以使用[无类别域间路由(CIDR)表示法](https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing#CIDR_notation)在索引中查询 IP 地址。使用 CIDR 表示法时,需要指定 IP 地址和前缀长度(0–32),两者用 `/` 分隔。例如,前缀长度为 24 时,将匹配前 24 位相同的所有 IP 地址。 + +#### IPv4 格式的查询示例 + +```json +GET testindex/_search +{ + "query": { + "term": { + "ip_address": "10.24.34.0/24" + } + } +} +``` + +#### IPv6 格式的查询示例 + +```json +GET testindex/_search +{ + "query": { + "term": { + "ip_address": "2001:DB8::/24" + } + } +} +``` + +如果在 `query_string` 查询中使用 IPv6 格式的 IP 地址,需要对 `:` 字符进行转义,因为它们会被解析为特殊字符。可以将 IP 地址用引号括起来,并用 `\` 对这些引号进行转义。 + +```json +GET testindex/_search +{ + "query" : { + "query_string": { + "query": "ip_address:\"2001:DB8::/24\"" + } + } +} +``` + +## 参数 + +下表列出了 ip 字段类型接受的参数。所有参数均为可选。 + +参数 | 描述 +:--- | :--- +`boost` | 一个浮点值,指定该字段对相关性评分(Relevance Score)的权重。大于 1.0 的值会提高该字段的相关性,介于 0.0 和 1.0 之间的值会降低该字段的相关性。默认值为 1.0。 +`doc_values` | 一个布尔值,指定是否将该字段存储到磁盘上,以便用于聚合、排序或脚本。默认值为 `true`。 +`ignore_malformed` | 一个布尔值,指定忽略格式错误的值而不抛出异常。默认值为 `false`。 +`index` | 一个布尔值,指定该字段是否可搜索。默认值为 `true`。 +[`null_value`](/field-types/supported-field-types/#null-value) | 用于替代 `null` 的值,必须与字段类型相同。如果未指定此参数,当字段值为 `null` 时,该字段会被视为缺失。默认值为 `null`。 +`store` | 一个布尔值,指定是否存储字段值,以便能独立于 _source 字段单独检索。默认值为 `false`。 diff --git a/i18n/zh/field-types/supported-field-types/join.md b/i18n/zh/field-types/supported-field-types/join.md new file mode 100644 index 00000000..ca76a46c --- /dev/null +++ b/i18n/zh/field-types/supported-field-types/join.md @@ -0,0 +1,310 @@ +--- +title: Join +--- + +# Join 字段类型 + +join 字段类型用于在同一索引(Index)中的文档(Document)之间建立父/子关系。 + +## 示例 + +创建一个映射(Mapping),在产品与其品牌之间建立父子关系: + +```json +PUT testindex1 +{ + "mappings": { + "properties": { + "product_to_brand": { + "type": "join", + "relations": { + "brand": "product" + } + } + } + } +} +``` + +然后,索引一个包含 join 字段类型的父文档: + +```json +PUT testindex1/_doc/1 +{ + "name": "Brand 1", + "product_to_brand": { + "name": "brand" + } +} +``` + +也可以使用不带对象表示法的简写形式来索引父文档: + +```json +PUT testindex1/_doc/1 +{ + "name": "Brand 1", + "product_to_brand" : "brand" +} +``` + +索引子文档时,必须指定 `routing` 查询参数,因为同一关系中的父文档和子文档必须索引到同一个分片(Shard)上。每个子文档都在 `parent` 字段中引用其父文档的 ID。 + +索引两个子文档,每个父文档各对应一个: + +```json +PUT testindex1/_doc/3?routing=1 +{ + "name": "Product 1", + "product_to_brand": { + "name": "product", + "parent": "1" + } +} +``` + +```json +PUT testindex1/_doc/4?routing=1 +{ + "name": "Product 2", + "product_to_brand": { + "name": "product", + "parent": "1" + } +} +``` + +## 查询 join 字段 + +查询 join 字段时,响应中会包含子字段,用于说明返回的文档是父文档还是子文档。对于子对象,还会返回父文档 ID。 + +### 搜索所有文档 + +```json +GET testindex1/_search +{ + "query": { + "match_all": {} + } +} +``` + +响应会指明文档是父文档还是子文档: + +```json +{ + "took" : 4, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 3, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "testindex1", + "_type" : "_doc", + "_id" : "1", + "_score" : 1.0, + "_source" : { + "name" : "Brand 1", + "product_to_brand" : { + "name" : "brand" + } + } + }, + { + "_index" : "testindex1", + "_type" : "_doc", + "_id" : "3", + "_score" : 1.0, + "_routing" : "1", + "_source" : { + "name" : "Product 1", + "product_to_brand" : { + "name" : "product", + "parent" : "1" + } + } + }, + { + "_index" : "testindex1", + "_type" : "_doc", + "_id" : "4", + "_score" : 1.0, + "_routing" : "1", + "_source" : { + "name" : "Product 2", + "product_to_brand" : { + "name" : "product", + "parent" : "1" + } + } + } + ] + } +} +``` + +### 搜索某个父文档的所有子文档 + +查找与 Brand 1 关联的所有产品: + +```json +GET testindex1/_search +{ + "query" : { + "has_parent": { + "parent_type":"brand", + "query": { + "match" : { + "name": "Brand 1" + } + } + } + } +} +``` + +响应包含与 Brand 1 关联的 Product 1 和 Product 2: + +```json +{ + "took" : 7, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 2, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "testindex1", + "_type" : "_doc", + "_id" : "3", + "_score" : 1.0, + "_routing" : "1", + "_source" : { + "name" : "Product 1", + "product_to_brand" : { + "name" : "product", + "parent" : "1" + } + } + }, + { + "_index" : "testindex1", + "_type" : "_doc", + "_id" : "4", + "_score" : 1.0, + "_routing" : "1", + "_source" : { + "name" : "Product 2", + "product_to_brand" : { + "name" : "product", + "parent" : "1" + } + } + } + ] + } +} +``` + +### 搜索某个子文档的父文档 + +查找 Product 1 的父文档: + +```json +GET testindex1/_search +{ + "query" : { + "has_child": { + "type":"product", + "query": { + "match" : { + "name": "Product 1" + } + } + } + } +} +``` + +响应返回 Brand 1 作为 Product 1 的父文档: + +```json +{ + "took" : 4, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "testindex1", + "_type" : "_doc", + "_id" : "1", + "_score" : 1.0, + "_source" : { + "name" : "Brand 1", + "product_to_brand" : { + "name" : "brand" + } + } + } + ] + } +} +``` + +## 具有多个子文档的父文档 + +一个父文档可以有多个子文档。创建一个包含多个子关系的映射: + +```json +PUT testindex1 +{ + "mappings": { + "properties": { + "parent_to_child": { + "type": "join", + "relations": { + "parent": ["child 1", "child 2"] + } + } + } + } +} +``` + +## Join 字段类型注意事项 + +- 一个索引中只能有一个 join 字段映射。 +- 检索、更新或删除子文档时,需要提供 routing 参数。这是因为同一关系中的父文档和子文档必须索引到同一个分片上。 +- 不支持多个父文档。 +- 只有当现有文档已被标记为父文档时,才能为其添加子文档。 +- 可以向现有的 join 字段添加新的关系。 diff --git a/i18n/zh/field-types/supported-field-types/keyword.md b/i18n/zh/field-types/supported-field-types/keyword.md new file mode 100644 index 00000000..5dd8d489 --- /dev/null +++ b/i18n/zh/field-types/supported-field-types/keyword.md @@ -0,0 +1,52 @@ +--- +title: Keyword +--- + +# Keyword 字段类型 + +keyword 字段类型包含不经过分析的字符串,只允许精确且区分大小写的匹配。 + +默认情况下,keyword 字段既会被索引(因为启用了 `index`),也会存储到磁盘上(因为启用了 `doc_values`)。为了减少磁盘空间占用,可以将 `index` 设置为 `false`,不对 keyword 字段建立索引。 + +::: info 注意 +如果需要将字段用于全文搜索,请将其映射为 [`text`](/field-types/supported-field-types/text)。 +::: + +## 示例 + +以下查询创建了一个包含 keyword 字段的映射(Mapping)。将 `index` 设置为 `false` 表示将 `genre` 字段存储在磁盘上,并通过 `doc_values` 检索: + +```json +PUT movies +{ + "mappings" : { + "properties" : { + "genre" : { + "type" : "keyword", + "index" : false + } + } + } +} +``` + +## 参数 + +下表列出了 keyword 字段类型接受的参数。所有参数均为可选。 + +参数 | 描述 +:--- | :--- +`boost` | 一个浮点值,指定该字段对相关性评分(Relevance Score)的权重。大于 1.0 的值会提高该字段的相关性,介于 0.0 和 1.0 之间的值会降低该字段的相关性。默认值为 1.0。 +`doc_values` | 一个布尔值,指定是否将该字段存储到磁盘上,以便用于聚合、排序或脚本。默认值为 `true`。 +`eager_global_ordinals` | 指定是否在刷新时预先加载全局序号(global ordinals)。如果该字段经常用于聚合,应将此参数设置为 `true`。默认值为 `false`。 +`fields` | 如需以多种方式索引同一个字符串(例如同时作为 keyword 和 text),请提供 fields 参数。可以指定字段的一个版本用于搜索,另一个版本用于排序和聚合。 +`ignore_above` | 长度超过该整数值的字符串不会被索引。默认值为 2147483647。默认的动态映射会创建一个 keyword 子字段,其 `ignore_above` 设置为 256。 +`index` | 一个布尔值,指定该字段是否可搜索。默认值为 `true`。为了减少磁盘空间占用,可将 `index` 设置为 `false`。 +`index_options` | 存储在索引中、计算相关性评分时会用到的信息。可以设置为 `freqs` 以存储词频。默认值为 `docs`。 +`meta` | 接受该字段的元数据。 +[`normalizer`](/analyzers/normalizers) | 指定在索引之前如何预处理该字段(例如转换为小写)。默认值为 `null`(不做预处理)。 +`norms` | 一个布尔值,指定在计算相关性评分时是否使用字段长度。默认值为 `false`。 +[`null_value`](/field-types/supported-field-types/#null-value) | 用于替代 `null` 的值,必须与字段类型相同。如果未指定此参数,当字段值为 `null` 时,该字段会被视为缺失。默认值为 `null`。 +`similarity` | 用于计算相关性评分的排序算法。默认值为 `BM25`。 +`split_queries_on_whitespace` | 一个布尔值,指定全文查询(Full-text Query)是否按空白字符拆分。默认值为 `false`。 +`store` | 一个布尔值,指定是否存储字段值,以便能独立于 `_source` 字段单独检索。默认值为 `false`。 diff --git a/i18n/zh/field-types/supported-field-types/knn-vector.md b/i18n/zh/field-types/supported-field-types/knn-vector.md new file mode 100644 index 00000000..24527942 --- /dev/null +++ b/i18n/zh/field-types/supported-field-types/knn-vector.md @@ -0,0 +1,260 @@ +--- +title: k-NN 向量 +--- + +# k-NN 向量字段类型 + +[k-NN 插件](/search-plugins/knn/)引入了一种自定义数据类型 `knn_vector`,允许用户将 k-NN 向量摄取到 OpenSearch 索引(Index)中,并执行各种 k-NN 搜索。`knn_vector` 字段的可配置性很强,能够满足多种不同的 k-NN 工作负载。通常,可以通过提供方法定义或指定模型 ID 来构建 `knn_vector` 字段。 + +## 示例 + +例如,要将 `my_vector1` 映射为 `knn_vector`,请使用以下请求: + +```json +PUT test-index +{ + "settings": { + "index": { + "knn": true, + "knn.algo_param.ef_search": 100 + } + }, + "mappings": { + "properties": { + "my_vector1": { + "type": "knn_vector", + "dimension": 3, + "method": { + "name": "hnsw", + "space_type": "l2", + "engine": "lucene", + "parameters": { + "ef_construction": 128, + "m": 24 + } + } + } + } + } +} +``` + +## 方法定义 + +当底层的[近似 k-NN](/search-plugins/knn/approximate-knn) 算法不需要训练时,使用[方法定义](/search-plugins/knn/knn-index#method-definitions)。例如,以下 `knn_vector` 字段指定使用 *nmslib* 的 *hnsw* 实现进行近似 k-NN 搜索。在索引过程中,*nmslib* 会构建相应的 *hnsw* 段文件。 + +```json +"my_vector": { + "type": "knn_vector", + "dimension": 4, + "method": { + "name": "hnsw", + "space_type": "l2", + "engine": "nmslib", + "parameters": { + "ef_construction": 128, + "m": 24 + } + } +} +``` + +## 模型 ID + +当底层的近似 k-NN 算法需要训练步骤时,使用模型 ID。前提是必须先使用 +[Train API](/search-plugins/knn/api#train-model) 创建模型。该 +模型包含初始化原生库段文件所需的信息。 + +```json + "type": "knn_vector", + "model_id": "my-model" +} +``` + +但是,如果打算使用 Painless 脚本或 k-NN 评分脚本,则只需传入维度。 + ```json + "type": "knn_vector", + "dimension": 128 + } + ``` + +## Lucene 字节向量 + +默认情况下,k-NN 向量是 `float` 向量,每个维度占 4 个字节。如果希望节省存储空间,可以在 `lucene` 引擎中使用 `byte` 向量。在 `byte` 向量中,每个维度都是取值范围为 [-128, 127] 的有符号 8 位整数。 + + +::: info 注意 +只有 `lucene` 引擎支持字节向量,`nmslib` 和 `faiss` 引擎不支持。 +::: + +在 [k-NN 基准测试](https://github.com/opensearch-project/k-NN/tree/main/benchmarks/perf-tool)中,使用 `byte` 向量代替 `float` 向量显著降低了存储和内存占用,同时提高了索引吞吐量并降低了查询延迟。此外,召回精度没有受到太大影响(请注意,召回率可能取决于多种因素,例如[量化技术](#quantization-techniques)和数据分布)。 + +::: warning 重要 +与使用 `float` 向量相比,使用 `byte` 向量时召回精度会有一定损失。字节向量适用于大规模应用,以及优先考虑降低内存占用、可以接受极小召回损失的使用场景。 +::: + + +k-NN 插件 2.9 版本引入了可选的 `data_type` 参数,用于定义向量的数据类型。该参数的默认值为 `float`。 + +如需使用 `byte` 向量,请在为索引创建映射(Mapping)时将 `data_type` 参数设置为 `byte`: + + ```json +PUT test-index +{ + "settings": { + "index": { + "knn": true, + "knn.algo_param.ef_search": 100 + } + }, + "mappings": { + "properties": { + "my_vector1": { + "type": "knn_vector", + "dimension": 3, + "data_type": "byte", + "method": { + "name": "hnsw", + "space_type": "l2", + "engine": "lucene", + "parameters": { + "ef_construction": 128, + "m": 24 + } + } + } + } + } +} +``` + +然后像往常一样摄取文档(Document)。请确保向量中的每个维度都在支持的 [-128, 127] 范围内: + +```json +PUT test-index/_doc/1 +{ + "my_vector1": [-126, 28, 127] +} +``` + +```json +PUT test-index/_doc/2 +{ + "my_vector1": [100, -128, 0] +} +``` + +查询时,请务必使用 `byte` 向量: + +```json +GET test-index/_search +{ + "size": 2, + "query": { + "knn": { + "my_vector1": { + "vector": [26, -120, 99], + "k": 2 + } + } + } +} +``` + +### 量化技术 + +如果向量是 `float` 类型,需要先将其转换为 `byte` 类型,然后再摄取文档。这种转换通过*对数据集进行量化*——即降低其向量的精度——来完成。量化技术有很多种,例如标量量化,或 Faiss 引擎中使用的乘积量化(PQ)。量化技术的选择取决于所使用的数据类型,并可能影响召回值的准确性。以下各节介绍了在 [k-NN 基准测试](https://github.com/opensearch-project/k-NN/tree/main/benchmarks/perf-tool)中,针对 [L2](#scalar-quantization-for-the-l2-space-type) 和[余弦相似度](#scalar-quantization-for-the-cosine-similarity-space-type)空间类型对测试数据进行量化时所使用的标量量化算法。所提供的伪代码仅用于说明。 + +#### L2 空间类型的标量量化 + +以下示例伪代码演示了在 L2 空间类型的欧几里得数据集上进行基准测试时所使用的标量量化技术。欧几里得距离具有平移不变性。如果将 $$x$$ 和 $$y$$ 同时平移相同的 $$z$$,距离保持不变($$\lVert x-y\rVert =\lVert (x-z)-(y-z)\rVert$$)。 + +```python +# 随机数据集(创建随机数据集的示例) +dataset = np.random.uniform(-300, 300, (100, 10)) +# 随机查询集(创建随机查询集的示例) +queryset = np.random.uniform(-350, 350, (100, 10)) +# 取值个数 +B = 256 + +# 索引: +# 获取最小值和最大值 +dataset_min = np.min(dataset) +dataset_max = np.max(dataset) +# 平移坐标,使其非负 +dataset -= dataset_min +# 归一化到 [0, 1] +dataset *= 1. / (dataset_max - dataset_min) +# 分桶为 256 个值 +dataset = np.floor(dataset * (B - 1)) - int(B / 2) + +# 查询: +# 裁剪(如果查询集的范围超出数据集的范围) +queryset = queryset.clip(dataset_min, dataset_max) +# 平移坐标,使其非负 +queryset -= dataset_min +# 归一化 +queryset *= 1. / (dataset_max - dataset_min) +# 分桶为 256 个值 +queryset = np.floor(queryset * (B - 1)) - int(B / 2) +``` + +#### 余弦相似度空间类型的标量量化 + +以下示例伪代码演示了在余弦相似度空间类型的角度数据集上进行基准测试时所使用的标量量化技术。余弦相似度不具有平移不变性($$cos(x, y) \neq cos(x-z, y-z)$$)。 + +以下伪代码适用于正数: + +```python +# 适用于正数 + +# 索引和查询: + +# 获取训练数据集的最大值 +max = np.max(dataset) +min = 0 +B = 127 + +# 归一化到 [0,1] +val = (val - min) / (max - min) +val = (val * B) + +# 获取整数部分和小数部分 +int_part = floor(val) +frac_part = val - int_part + +if 0.5 < frac_part: + bval = int_part + 1 +else: + bval = int_part + +return Byte(bval) +``` + +以下伪代码适用于负数: + +```python +# 适用于负数 + +# 索引和查询: + +# 获取训练数据集的最小值 +min = 0 +max = -np.min(dataset) +B = 128 + +# 归一化到 [0,1] +val = (val - min) / (max - min) +val = (val * B) + +# 获取整数部分和小数部分 +int_part = floor(var) +frac_part = val - int_part + +if 0.5 < frac_part: + bval = int_part + 1 +else: + bval = int_part + +return Byte(bval) +``` diff --git a/i18n/zh/field-types/supported-field-types/match-only-text.md b/i18n/zh/field-types/supported-field-types/match-only-text.md new file mode 100644 index 00000000..db121da5 --- /dev/null +++ b/i18n/zh/field-types/supported-field-types/match-only-text.md @@ -0,0 +1,93 @@ +--- +title: 仅匹配文本 +--- + +# 仅匹配文本字段类型 + +`match_only_text` 字段是 `text` 字段的一种变体,适用于不太关心评分以及词项在文档中位置信息的全文搜索场景。 + +`match_only_text` 字段与 `text` 字段有以下不同: + + - 不存储位置、频率和规范化因子(norms),从而降低存储需求。 + - 禁用评分,所有匹配的文档都获得恒定的 1.0 分。 + - 支持除 interval 查询和 span 查询之外的所有查询类型。 + +如果希望优先考虑高效的全文搜索而非复杂的排序和位置查询,同时优化存储成本,可以选择 `match_only_text` 字段类型。使用 `match_only_text` 创建的索引会显著变小,从而降低存储成本,对于大型数据集尤其如此。 + +当需要快速查找包含特定词项的文档,而又不想承担存储频率和位置信息的开销时,可以使用 `match_only_text` 字段。如果需要根据相关性对结果排序,或者需要依赖词项邻近度或顺序的查询(例如 interval 查询或 span 查询),`match_only_text` 字段类型并不是最佳选择。虽然该字段类型支持短语查询,但其性能不如使用 `text` 字段类型时高效。如果识别精确短语或其在文档中的位置至关重要,请改用 `text` 字段类型。 + +## 示例 + +创建一个包含 `match_only_text` 字段的映射(Mapping): + +```json +PUT movies +{ + "mappings" : { + "properties" : { + "title" : { + "type" : "match_only_text" + } + } + } +} +``` + +## 参数 + +虽然 `match_only_text` 支持 `text` 字段的大部分参数,但修改其中的大多数参数可能会适得其反。该字段类型的设计初衷是简单高效,尽量减少索引中存储的数据以优化存储成本。因此,通常最好保持默认设置。除分析器(Analyzer)设置之外的任何修改都可能重新引入开销,抵消 `match_only_text` 带来的效率优势。 + +下表列出了 `match_text_only` 字段可用的所有参数。 + +参数 | 描述 +:--- | :--- +`analyzer` | 该字段使用的分析器。默认情况下,它在索引时和搜索时都会使用。如需在搜索时覆盖,请设置 `search_analyzer` 参数。默认值为 `standard` 分析器,它使用基于语法的分词,并基于 [Unicode Text Segmentation](https://unicode.org/reports/tr29/) 算法。 +`boost` | 所有命中(Hit)的评分都为 1,再乘以 `boost` 得到该查询子句的最终评分。 +`eager_global_ordinals` | 指定是否在刷新时预先加载全局序号(global ordinals)。如果该字段经常用于聚合,应将此参数设置为 `true`。默认值为 `false`。 +`fielddata` | 一个布尔值,指定是否可以访问分析后的词元(Token)用于排序、聚合和脚本。默认值为 `false`。 +`fielddata_frequency_filter` | 一个 JSON 对象,指定只将文档频率介于 `min` 和 `max` 值(可以是绝对数值或百分比)之间的分析后词元加载到内存中。频率按段计算。参数:`min`、`max`、`min_segment_size`。默认加载所有分析后的词元。 +`fields` | 如需以多种方式索引同一个字符串(例如同时作为 keyword 和 text),请提供 `fields` 参数。可以指定字段的一个版本用于搜索,另一个版本用于排序和聚合。 +`index` | 一个布尔值,指定该字段是否可搜索。默认值为 `true`。 +`index_options` | 不能修改此参数。 +`index_phrases` | 不支持。 +`index_prefixes` | 不支持。 +`meta` | 接受该字段的元数据。 +`norms` | 规范化因子(norms)已禁用,且无法启用。 +`position_increment_gap` | 虽然位置信息已禁用,但在短语查询中使用时,`position_increment_gap` 的行为与 `text` 字段类似。此类查询可能较慢,但仍可正常工作。 +`similarity` | 设置相似度没有任何作用。`match_only_text` 字段类型不支持 `more_like_this` 等依赖相似度的查询。对于依赖相似度的查询,请使用 `keyword` 或 `text` 字段。 +`term_vector` | 支持词项向量(term vector),但不建议使用,因为这与该字段的主要目的——存储优化——相悖。 + +## 将字段从 `text` 迁移到 `match_only_text` + +可以使用 [Reindex API](/api-reference/document-apis/reindex) 从 `text` 字段迁移到 `match_only_text`,方法是在目标索引中更新为正确的映射。 + +在以下示例中,`source` 索引包含一个类型为 `text` 的 `title` 字段。 + +创建一个目标索引,其中 `title` 字段映射为 `text`: + +```json +PUT destination +{ + "mappings" : { + "properties" : { + "title" : { + "type" : "match_only_text" + } + } + } +} +``` + +重新索引数据: + +```json +POST _reindex +{ + "source": { + "index":"source" + }, + "dest": { + "index":"destination" + } +} +``` diff --git a/i18n/zh/field-types/supported-field-types/nested.md b/i18n/zh/field-types/supported-field-types/nested.md new file mode 100644 index 00000000..ea6e216d --- /dev/null +++ b/i18n/zh/field-types/supported-field-types/nested.md @@ -0,0 +1,299 @@ +--- +title: Nested +--- + +# Nested 字段类型 + +nested 字段类型是一种特殊的[对象字段类型](/field-types/supported-field-types/object)。 + +任何对象字段都可以接受一个对象数组。数组中的每个对象都会被动态映射为对象字段类型,并以扁平化的形式存储。这意味着数组中的对象会被拆分为各个单独的字段,所有对象中同一字段的值会存储在一起。有时需要使用 nested 类型将嵌套对象作为一个整体保留下来,以便对其执行搜索。 + +## 扁平化形式 + +默认情况下,每个嵌套对象都会被动态映射为对象字段类型。任何对象字段都可以接受一个对象数组。 + +```json +PUT testindex1/_doc/100 +{ + "patients": [ + {"name" : "John Doe", "age" : 56, "smoker" : true}, + {"name" : "Mary Major", "age" : 85, "smoker" : false} + ] +} +``` + +存储这些对象时,它们会被扁平化,因此其内部表示中每个字段都对应一个包含所有值的数组: + +```json +{ + "patients.name" : ["John Doe", "Mary Major"], + "patients.age" : [56, 85], + "patients.smoker" : [true, false] +} +``` + +在这种表示形式下,有些查询(Query)可以正确执行。如果搜索年龄大于 75 岁或吸烟的病人,文档(Document)100 应当匹配。 + +```json +GET testindex1/_search +{ + "query": { + "bool": { + "should": [ + { + "term": { + "patients.smoker": true + } + }, + { + "range": { + "patients.age": { + "gte": 75 + } + } + } + ] + } + } +} +``` + +该查询正确地返回了文档 100: + +```json +{ + "took" : 3, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 1.3616575, + "hits" : [ + { + "_index" : "testindex1", + "_type" : "_doc", + "_id" : "100", + "_score" : 1.3616575, + "_source" : { + "patients" : [ + { + "name" : "John Doe", + "age" : "56", + "smoker" : true + }, + { + "name" : "Mary Major", + "age" : "85", + "smoker" : false + } + ] + } + } + ] + } +} +``` + +而如果搜索年龄大于 75 岁且吸烟的病人,文档 100 不应当匹配。 + +```json +GET testindex1/_search +{ + "query": { + "bool": { + "must": [ + { + "term": { + "patients.smoker": true + } + }, + { + "range": { + "patients.age": { + "gte": 75 + } + } + } + ] + } + } +} +``` + +然而,该查询仍然错误地返回了文档 100。这是因为在为各个字段创建值数组时,年龄与吸烟之间的关联丢失了。 + +## Nested 字段类型 {#nested-field-type-1} + +嵌套对象会作为单独的文档存储,父对象持有对其子对象的引用。如需将对象标记为嵌套对象,请创建一个包含 nested 字段类型的映射(Mapping)。 + +```json +PUT testindex1 +{ + "mappings" : { + "properties": { + "patients": { + "type" : "nested" + } + } + } +} +``` + +然后,索引一个包含 nested 字段类型的文档: + +```json +PUT testindex1/_doc/100 +{ + "patients": [ + {"name" : "John Doe", "age" : 56, "smoker" : true}, + {"name" : "Mary Major", "age" : 85, "smoker" : false} + ] +} +``` + +可以使用以下 nested 查询来搜索年龄大于 75 岁或吸烟的病人: + +```json +GET testindex1/_search +{ + "query": { + "nested": { + "path": "patients", + "query": { + "bool": { + "should": [ + { + "term": { + "patients.smoker": true + } + }, + { + "range": { + "patients.age": { + "gte": 75 + } + } + } + ] + } + } + } + } +} +``` + +该查询正确地返回了两个病人: + +```json +{ + "took" : 7, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 0.8465736, + "hits" : [ + { + "_index" : "testindex1", + "_id" : "100", + "_score" : 0.8465736, + "_source" : { + "patients" : [ + { + "name" : "John Doe", + "age" : 56, + "smoker" : true + }, + { + "name" : "Mary Major", + "age" : 85, + "smoker" : false + } + ] + } + } + ] + } +} +``` + +可以使用以下 nested 查询来搜索年龄大于 75 岁且吸烟的病人: + +```json +GET testindex1/_search +{ + "query": { + "nested": { + "path": "patients", + "query": { + "bool": { + "must": [ + { + "term": { + "patients.smoker": true + } + }, + { + "range": { + "patients.age": { + "gte": 75 + } + } + } + ] + } + } + } + } +} +``` + +与预期一致,上述查询没有返回任何结果: + +```json +{ + "took" : 7, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 0, + "relation" : "eq" + }, + "max_score" : null, + "hits" : [ ] + } +} +``` + +## 参数 + +下表列出了对象字段类型接受的参数。所有参数均为可选。 + +参数 | 描述 +:--- | :--- +[`dynamic`](/field-types/supported-field-types/object#the-dynamic-parameter) | 指定是否可以向该对象动态添加新字段。有效值为 `true`、`false` 和 `strict`。默认值为 `true`。 +`include_in_parent` | 一个布尔值,指定是否也将子嵌套对象中的所有字段以扁平化形式添加到父文档中。默认值为 `false`。 +`include_in_root` | 一个布尔值,指定是否也将子嵌套对象中的所有字段以扁平化形式添加到根文档中。默认值为 `false`。 +`properties` | 该对象的字段,可以是任何受支持的类型。如果 `dynamic` 设置为 `true`,则可以向该对象动态添加新属性。 diff --git a/i18n/zh/field-types/supported-field-types/numeric.md b/i18n/zh/field-types/supported-field-types/numeric.md new file mode 100644 index 00000000..a33ceb2b --- /dev/null +++ b/i18n/zh/field-types/supported-field-types/numeric.md @@ -0,0 +1,111 @@ +--- +title: 数值字段类型 +--- + +# 数值字段类型 + +下表列出了 OpenSearch 支持的所有数值字段类型。 + +字段数据类型 | 描述 +:--- | :--- +`byte` | 有符号 8 位整数。最小值为 −128,最大值为 127。 +`double` | 双精度 64 位 IEEE 754 浮点值。最小绝对值为 2−1074 ,最大绝对值为 (2 − 2−52) · 21023。有效位数为 53 位,有效数字为 15.95 位。 +`float` | 单精度 32 位 IEEE 754 浮点值。最小绝对值为 2−149 ,最大绝对值为 (2 − 2−23) · 2127。有效位数为 24 位,有效数字为 7.22 位。 +`half_float` | 半精度 16 位 IEEE 754 浮点值。最小绝对值为 2−24 ,最大绝对值为 65504。有效位数为 11 位,有效数字为 3.31 位。 +`integer` | 有符号 32 位整数。最小值为 −231,最大值为 231 − 1。 +`long` | 有符号 64 位整数。最小值为 −263,最大值为 263 − 1。 +[`unsigned_long`](/field-types/supported-field-types/unsigned-long) | 无符号 64 位整数。最小值为 0,最大值为 264 − 1。 +`short` | 有符号 16 位整数。最小值为 −215,最大值为 215 − 1。 +[`scaled_float`](#scaled-float-field-type) | 一个浮点值,乘以 double 类型的缩放因子后以 long 值存储。 + +::: info 注意 +integer、long、float 和 double 字段类型都有对应的[范围字段类型](/field-types/supported-field-types/range)。 +::: + +::: tip 提示 +如果数值字段包含 ID 之类的标识符,可以将该字段映射为 [keyword](/field-types/supported-field-types/keyword),以优化词项级查询(Term-level Query)的速度。如果还需要对该字段使用范围查询,可以在 keyword 字段类型之外,再将该字段映射为数值字段类型。 +::: + +## 示例 + +创建一个映射(Mapping),其中 integer_value 是一个 integer 字段: + +```json +PUT testindex +{ + "mappings" : { + "properties" : { + "integer_value" : { + "type" : "integer" + } + } + } +} +``` + +索引一个包含整数值的文档(Document): + +```json +PUT testindex/_doc/1 +{ + "integer_value" : 123 +} +``` + +## 缩放浮点字段类型 + +缩放浮点(scaled float)字段类型是一个浮点值,乘以缩放因子后以 long 值存储。它接受数值字段类型的所有可选参数,另外还有一个 scaling_factor 参数。创建缩放浮点字段时必须指定缩放因子。 + +::: info 注意 +缩放浮点有助于节省磁盘空间。scaling_factor 值越大,精度越高,但空间开销也越大。 +::: + +## 缩放浮点示例 + +创建一个映射,其中 `scaled` 是一个 scaled_float 字段: + +```json +PUT testindex +{ + "mappings" : { + "properties" : { + "scaled" : { + "type" : "scaled_float", + "scaling_factor" : 10 + } + } + } +} +``` + +索引一个包含 scaled_float 值的文档: + +```json +PUT testindex/_doc/1 +{ + "scaled" : 2.3 +} +``` + +`scaled` 值将存储为 23。 + +## 参数 + +下表列出了数值字段类型接受的参数。所有参数均为可选。 + +参数 | 描述 +:--- | :--- +`boost` | 一个浮点值,指定该字段对相关性评分(Relevance Score)的权重。大于 1.0 的值会提高该字段的相关性,介于 0.0 和 1.0 之间的值会降低该字段的相关性。默认值为 1.0。 +`coerce` | 一个布尔值,表示对整数值截断小数部分,并将字符串转换为数值。默认值为 `true`。 +`doc_values` | 一个布尔值,指定是否将该字段存储到磁盘上,以便用于聚合、排序或脚本。默认值为 `true`。 +`ignore_malformed` | 一个布尔值,指定忽略格式错误的值而不抛出异常。默认值为 `false`。 +`index` | 一个布尔值,指定该字段是否可搜索。默认值为 `true`。 +`meta` | 接受该字段的元数据。 +[`null_value`](/field-types/supported-field-types/#null-value) | 用于替代 `null` 的值,必须与字段类型相同。如果未指定此参数,当字段值为 `null` 时,该字段会被视为缺失。默认值为 `null`。 +`store` | 一个布尔值,指定是否存储字段值,以便能独立于 _source 字段单独检索。默认值为 `false`。 + +缩放浮点还有一个必需参数:`scaling_factor`。 + +参数 | 描述 +:--- | :--- +`scaling_factor` | 一个 double 值,与字段值相乘后四舍五入为最接近的 long 值。必需。 diff --git a/i18n/zh/field-types/supported-field-types/object-fields.md b/i18n/zh/field-types/supported-field-types/object-fields.md new file mode 100644 index 00000000..40a4bde2 --- /dev/null +++ b/i18n/zh/field-types/supported-field-types/object-fields.md @@ -0,0 +1,14 @@ +--- +title: 对象字段类型 +--- + +# 对象字段类型 + +对象字段类型(Object Field Type)包含对象或关系类型的值。下表列出了 OpenSearch 支持的所有对象字段类型。 + +字段数据类型 | 描述 +:--- | :--- +[`object`](/field-types/supported-field-types/object) | JSON 对象。 +[`nested`](/field-types/supported-field-types/nested) | 当数组中的对象需要作为单独的文档独立索引时使用。 +[`flat_object`](/field-types/supported-field-types/flat-object) | 被视为字符串的 JSON 对象。 +[`join`](/field-types/supported-field-types/join) | 在同一索引中的文档之间建立父子关系。 diff --git a/i18n/zh/field-types/supported-field-types/object.md b/i18n/zh/field-types/supported-field-types/object.md new file mode 100644 index 00000000..441e1eb0 --- /dev/null +++ b/i18n/zh/field-types/supported-field-types/object.md @@ -0,0 +1,142 @@ +--- +title: Object +--- + +# Object 字段类型 + +object 字段类型包含一个 JSON 对象(一组名称/值对)。JSON 对象中的值可以是另一个 JSON 对象。映射对象字段时不需要将类型指定为 `object`,因为 `object` 是默认类型。 + +## 示例 + +创建一个包含对象字段的映射(Mapping): + +```json +PUT testindex1/_mappings +{ + "properties": { + "patient": { + "properties" : + { + "name" : { + "type" : "text" + }, + "id" : { + "type" : "keyword" + } + } + } + } +} +``` + +索引一个包含对象字段的文档(Document): + +```json +PUT testindex1/_doc/1 +{ + "patient": { + "name" : "John Doe", + "id" : "123456" + } +} +``` + +嵌套对象在内部以扁平的键/值对形式存储。如需引用嵌套对象中的字段,请使用 `parent field`.`child field` 的形式(例如 `patient.id`)。 + +搜索 ID 为 123456 的病人: + +```json +GET testindex1/_search +{ + "query": { + "term" : { + "patient.id" : "123456" + } + } +} +``` + +## 参数 + +下表列出了 object 字段类型接受的参数。所有参数均为可选。 + +参数 | 描述 +:--- | :--- +[`dynamic`](#the-dynamic-parameter) | 指定是否可以向该对象动态添加新字段。有效值为 `true`、`false` 和 `strict`。默认值为 `true`。 +`enabled` | 一个布尔值,指定是否解析该对象的 JSON 内容。如果 `enabled` 设置为 `false`,该对象的内容不会被索引,也无法搜索,但仍然可以从 _source 字段中检索。默认值为 `true`。 +`properties` | 该对象的字段,可以是任何受支持的类型。如果 `dynamic` 设置为 `true`,则可以向该对象动态添加新属性。 + +### `dynamic` 参数 + +`dynamic` 参数指定是否可以向已索引的对象动态添加新字段。 + +例如,可以先创建一个映射,其中 `patient` 对象只有一个字段: + +```json +PUT testindex1/_mappings +{ + "properties": { + "patient": { + "properties" : + { + "name" : { + "type" : "text" + } + } + } + } +} +``` + +然后索引一个文档,在 `patient` 中包含一个新的 `id` 字段: + +```json +PUT testindex1/_doc/1 +{ + "patient": { + "name" : "John Doe", + "id" : "123456" + } +} +``` + +结果,`id` 字段被添加到了映射中: + +```json +{ + "testindex1" : { + "mappings" : { + "properties" : { + "patient" : { + "properties" : { + "id" : { + "type" : "text", + "fields" : { + "keyword" : { + "type" : "keyword", + "ignore_above" : 256 + } + } + }, + "name" : { + "type" : "text" + } + } + } + } + } + } +} +``` + +`dynamic` 参数有以下有效值。 + +值 | 描述 +:--- | :--- +`true` | 可以向映射动态添加新字段。这是默认值。 +`false` | 不能向映射动态添加新字段。如果检测到新字段,该字段不会被索引,也无法搜索,但仍然可以从 _source 字段中检索。 +`strict` | 当向映射动态添加新字段时,会抛出异常。如需向对象添加新字段,必须先将其添加到映射中。 + +::: info 注意 +内部对象会继承父对象的 `dynamic` 参数值,除非它们声明了自己的 `dynamic` 参数值。 +::: diff --git a/i18n/zh/field-types/supported-field-types/percolator.md b/i18n/zh/field-types/supported-field-types/percolator.md new file mode 100644 index 00000000..7326d319 --- /dev/null +++ b/i18n/zh/field-types/supported-field-types/percolator.md @@ -0,0 +1,151 @@ +--- +title: Percolator +--- + +# Percolator 字段类型 + +percolator 字段类型指定将该字段视为查询(Query)。任何 JSON 对象字段都可以标记为 percolator 字段。通常的做法是先索引文档(Document),然后针对这些文档执行搜索。而使用 percolator 字段时,是先存储一个搜索,之后由 percolate 查询将文档与该搜索进行匹配。 + +## 示例 + +一位顾客正在搜索价格不超过 400 美元的桌子,并希望为该搜索创建一个提醒。 + +创建一个映射(Mapping),为 query 字段指定 percolator 字段类型: + +```json +PUT testindex1 +{ + "mappings": { + "properties": { + "search": { + "properties": { + "query": { + "type": "percolator" + } + } + }, + "price": { + "type": "float" + }, + "item": { + "type": "text" + } + } + } +} +``` + +索引一个查询: + +```json +PUT testindex1/_doc/1 +{ + "search": { + "query": { + "bool": { + "filter": [ + { + "match": { + "item": { + "query": "table" + } + } + }, + { + "range": { + "price": { + "lte": 400.00 + } + } + } + ] + } + } + } +} +``` + +::: info 注意 +查询中引用的字段必须已经存在于映射中。 +::: + +运行 percolate 查询以搜索匹配的文档: + +```json +GET testindex1/_search +{ + "query" : { + "bool" : { + "filter" : + { + "percolate" : { + "field" : "search.query", + "document" : { + "item" : "Mahogany table", + "price": 399.99 + } + } + } + } + } +} +``` + +响应中包含最初索引的查询: + +```json +{ + "took" : 30, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 0.0, + "hits" : [ + { + "_index" : "testindex1", + "_type" : "_doc", + "_id" : "1", + "_score" : 0.0, + "_source" : { + "search" : { + "query" : { + "bool" : { + "filter" : [ + { + "match" : { + "item" : { + "query" : "table" + } + } + }, + { + "range" : { + "price" : { + "lte" : 400.0 + } + } + } + ] + } + } + } + }, + "fields" : { + "_percolator_document_slot" : [ + 0 + ] + } + } + ] + } +} +``` diff --git a/i18n/zh/field-types/supported-field-types/range.md b/i18n/zh/field-types/supported-field-types/range.md new file mode 100644 index 00000000..13fc33d3 --- /dev/null +++ b/i18n/zh/field-types/supported-field-types/range.md @@ -0,0 +1,146 @@ +--- +title: 范围字段类型 +--- + +# 范围字段类型 + +下表列出了 OpenSearch 支持的所有范围字段类型。 + +字段数据类型 | 描述 +:--- | :--- +`integer_range` | [integer](/field-types/supported-field-types/numeric) 值的范围。 +`long_range` | [long](/field-types/supported-field-types/numeric) 值的范围。 +`double_range` | [double](/field-types/supported-field-types/numeric) 值的范围。 +`float_range` | [float](/field-types/supported-field-types/numeric) 值的范围。 +`ip_range` | IPv4 或 IPv6 格式的 [IP 地址](/field-types/supported-field-types/ip)范围。起始和结束 IP 地址可以采用不同的格式。 +`date_range` | [date](/field-types/supported-field-types/date) 值的范围。起始和结束日期可以采用不同的[格式](/field-types/supported-field-types/date#formats)。在内部,所有日期都存储为无符号 64 位整数,表示自纪元(epoch)以来的毫秒数。 + +## 示例 + +创建一个包含 double 范围和 date 范围的映射(Mapping): + +```json +PUT testindex +{ + "mappings" : { + "properties" : { + "gpa" : { + "type" : "double_range" + }, + "graduation_date" : { + "type" : "date_range", + "format" : "strict_year_month||strict_year_month_day" + } + } + } +} +``` + +索引一个包含 double 范围和 date 范围的文档(Document): + +```json +PUT testindex/_doc/1 +{ + "gpa" : { + "gte" : 1.0, + "lte" : 4.0 + }, + "graduation_date" : { + "gte" : "2019-05-01", + "lte" : "2019-05-15" + } +} +``` + +## IP 地址范围 + +可以用两种格式指定 IP 地址范围:范围格式和 [CIDR 表示法](https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing#CIDR_notation)。 + +创建一个包含 IP 地址范围的映射: + +```json +PUT testindex +{ + "mappings" : { + "properties" : { + "ip_address_range" : { + "type" : "ip_range" + }, + "ip_address_cidr" : { + "type" : "ip_range" + } + } + } +} +``` + +索引一个包含两种格式 IP 地址范围的文档: + +```json +PUT testindex/_doc/2 +{ + "ip_address_range" : { + "gte" : "10.24.34.0", + "lte" : "10.24.35.255" + }, + "ip_address_cidr" : "10.24.34.0/24" +} +``` + +## 查询范围字段 + +可以使用 [term 查询](#term-query)或 [range 查询](#range-query)在范围字段中搜索值。 + +### Term 查询 + +term 查询接受一个值,并匹配该值落在其范围内的所有范围字段。 + +以下查询将返回文档 1,因为 3.5 落在范围 [1.0, 4.0] 之内: + +```json +GET testindex/_search +{ + "query" : { + "term" : { + "gpa" : { + "value" : 3.5 + } + } + } +} +``` + +### Range 查询 + +对范围字段执行 range 查询会返回位于该范围内的文档。 + +查询 2019 年的所有毕业日期,以 "MM/dd/yyyy" 格式提供日期范围: + +```json +GET testindex1/_search +{ + "query": { + "range": { + "graduation_date": { + "gte": "01/01/2019", + "lte": "12/31/2019", + "format": "MM/dd/yyyy", + "relation" : "within" + } + } + } +} +``` + +对于 `within` 和 `intersects` 关系,上述查询会返回文档 1;对于 `contains` 关系则不会返回。有关关系类型的更多信息,请参阅 [range 查询参数](/query-dsl/term/range#parameters)。 + +## 参数 + +下表列出了范围字段类型接受的参数。所有参数均为可选。 + +参数 | 描述 +:--- | :--- +`boost` | 一个浮点值,指定该字段对相关性评分(Relevance Score)的权重。大于 1.0 的值会提高该字段的相关性,介于 0.0 和 1.0 之间的值会降低该字段的相关性。默认值为 1.0。 +`coerce` | 一个布尔值,表示对整数值截断小数部分,并将字符串转换为数值。默认值为 `true`。 +`index` | 一个布尔值,指定该字段是否可搜索。默认值为 `true`。 +`store` | 一个布尔值,指定是否存储字段值,以便能独立于 _source 字段单独检索。默认值为 `false`。 diff --git a/i18n/zh/field-types/supported-field-types/rank.md b/i18n/zh/field-types/supported-field-types/rank.md new file mode 100644 index 00000000..17d651f5 --- /dev/null +++ b/i18n/zh/field-types/supported-field-types/rank.md @@ -0,0 +1,268 @@ +--- +title: 排名字段类型 +--- + +# 排名字段类型 + +下表列出了 OpenSearch 支持的所有排名(rank)字段类型。 + +字段数据类型 | 描述 +:--- | :--- +[`rank_feature`](#rank-feature) | 提高或降低文档的相关性评分(Relevance Score)。 +[`rank_features`](#rank-features) | 提高或降低文档的相关性评分。在特征列表稀疏时使用。 + +::: info 注意 +rank feature 和 rank features 字段只能通过 [rank feature 查询](#rank-feature-query)进行查询,不支持聚合或排序。 +::: + +## Rank feature + +rank feature 字段类型使用一个正的 [float](/field-types/supported-field-types/numeric) 值,在 `rank_feature` 查询中提高或降低文档的相关性评分。默认情况下,该值会提高相关性评分。如需降低相关性评分,请将可选参数 `positive_score_impact` 设置为 false。 + +### 示例 + +创建一个包含 rank feature 字段的映射(Mapping): + +```json +PUT chessplayers +{ + "mappings": { + "properties": { + "name" : { + "type" : "text" + }, + "rating": { + "type": "rank_feature" + }, + "age": { + "type": "rank_feature", + "positive_score_impact": false + } + } + } +} +``` + +索引三个文档,其中包含一个提高评分的 rank_feature 字段(`rating`)和一个降低评分的 rank_feature 字段(`age`): + +```json +PUT testindex1/_doc/1 +{ + "name" : "John Doe", + "rating" : 2554, + "age" : 75 +} +``` + +```json +PUT testindex1/_doc/2 +{ + "name" : "Kwaku Mensah", + "rating" : 2067, + "age": 10 +} +``` + +```json +PUT testindex1/_doc/3 +{ + "name" : "Nikki Wolf", + "rating" : 1864, + "age" : 22 +} +``` + +## Rank feature 查询 + +使用 rank feature 查询,可以按等级分、按年龄或同时按等级分和年龄对棋手进行排名。如果按等级分排名,等级分越高的棋手相关性评分越高;如果按年龄排名,越年轻的棋手相关性评分越高。 + +使用 rank feature 查询,根据年龄和等级分搜索棋手: + +```json +GET chessplayers/_search +{ + "query": { + "bool": { + "should": [ + { + "rank_feature": { + "field": "rating" + } + }, + { + "rank_feature": { + "field": "age" + } + } + ] + } + } +} +``` + +同时按年龄和等级分排名时,越年轻、等级越高的棋手得分越高: + +```json +{ + "took" : 2, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 3, + "relation" : "eq" + }, + "max_score" : 1.2093145, + "hits" : [ + { + "_index" : "chessplayers", + "_type" : "_doc", + "_id" : "2", + "_score" : 1.2093145, + "_source" : { + "name" : "Kwaku Mensah", + "rating" : 1967, + "age" : 10 + } + }, + { + "_index" : "chessplayers", + "_type" : "_doc", + "_id" : "3", + "_score" : 1.0150313, + "_source" : { + "name" : "Nikki Wolf", + "rating" : 1864, + "age" : 22 + } + }, + { + "_index" : "chessplayers", + "_type" : "_doc", + "_id" : "1", + "_score" : 0.8098284, + "_source" : { + "name" : "John Doe", + "rating" : 2554, + "age" : 75 + } + } + ] + } +} +``` + +## Rank features + +rank features 字段类型与 rank feature 字段类型类似,但更适合稀疏的特征列表。rank features 字段可以索引数值特征向量,这些向量之后会在 `rank_feature` 查询中用于提高或降低文档的相关性评分。 + +### 示例 {#example-1} + +创建一个包含 rank features 字段的映射: + +```json +PUT testindex1 +{ + "mappings": { + "properties": { + "correlations": { + "type": "rank_features" + } + } + } +} +``` + +要索引包含 rank features 字段的文档,请使用键为字符串、值为正浮点数的哈希映射(hashmap): + +```json +PUT testindex1/_doc/1 +{ + "correlations": { + "young kids" : 1, + "older kids" : 15, + "teens" : 25.9 + } +} +``` + +```json +PUT testindex1/_doc/2 +{ + "correlations": { + "teens": 10, + "adults": 95.7 + } +} +``` + +使用 rank feature 查询来查询文档: + +```json +GET testindex1/_search +{ + "query": { + "rank_feature": { + "field": "correlations.teens" + } + } +} +``` + +响应按相关性评分排序: + +```json +{ + "took" : 123, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 2, + "relation" : "eq" + }, + "max_score" : 0.6258503, + "hits" : [ + { + "_index" : "testindex1", + "_type" : "_doc", + "_id" : "1", + "_score" : 0.6258503, + "_source" : { + "correlations" : { + "young kids" : 1, + "older kids" : 15, + "teens" : 25.9 + } + } + }, + { + "_index" : "testindex1", + "_type" : "_doc", + "_id" : "2", + "_score" : 0.39263803, + "_source" : { + "correlations" : { + "teens" : 10, + "adults" : 95.7 + } + } + } + ] + } +} +``` + +::: info 注意 +rank feature 和 rank features 字段使用最高的 9 个有效位来表示精度,因此会产生约 0.4% 的相对误差。值以 2−8 = 0.00390625 的相对精度存储。 +::: diff --git a/i18n/zh/field-types/supported-field-types/search-as-you-type.md b/i18n/zh/field-types/supported-field-types/search-as-you-type.md new file mode 100644 index 00000000..1ac269d3 --- /dev/null +++ b/i18n/zh/field-types/supported-field-types/search-as-you-type.md @@ -0,0 +1,198 @@ +--- +title: 边输入边搜索 +--- + +# Search-as-you-type 字段类型 + +search-as-you-type 字段类型同时利用前缀补全和中缀补全,提供边输入边搜索(search-as-you-type)功能。 + +## 示例 + +为 search-as-you-type 字段建立映射(Mapping)时,会为该字段创建 n-gram 子字段,其中 n 的取值范围为 [2, `max_shingle_size`]。此外,还会创建一个索引前缀子字段。 + +创建一个包含 search-as-you-type 字段的映射: + +```json +PUT books +{ + "mappings": { + "properties": { + "suggestions": { + "type": "search_as_you_type" + } + } + } +} +``` + +除 `suggestions` 字段外,上述操作还会创建 `suggestions._2gram`、`suggestions._3gram` 和 `suggestions._index_prefix` 字段。 + +索引一个包含 search-as-you-type 字段的文档(Document): + +```json +PUT books/_doc/1 +{ + "suggestions": "one two three four" +} +``` + +要以任意顺序匹配词项,请使用 bool_prefix 或 multi-match 查询(Query)。这些查询会将搜索词按指定顺序出现的文档排在搜索词顺序不一致的文档之前。 + +```json +GET books/_search +{ + "query": { + "multi_match": { + "query": "tw one", + "type": "bool_prefix", + "fields": [ + "suggestions", + "suggestions._2gram", + "suggestions._3gram" + ] + } + } +} +``` + +响应中包含匹配的文档: + +```json +{ + "took" : 13, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "books", + "_type" : "_doc", + "_id" : "1", + "_score" : 1.0, + "_source" : { + "suggestions" : "one two three four" + } + } + ] + } +} +``` + +要按顺序匹配词项,请使用 match_phrase_prefix 查询: + +```json +GET books/_search +{ + "query": { + "match_phrase_prefix": { + "suggestions": "two th" + } + } +} +``` + +响应中包含匹配的文档: + +```json +{ + "took" : 23, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 0.4793051, + "hits" : [ + { + "_index" : "books", + "_type" : "_doc", + "_id" : "1", + "_score" : 0.4793051, + "_source" : { + "suggestions" : "one two three four" + } + } + ] + } +} +``` + +要精确匹配最后的词项,请使用 match_phrase 查询: + +```json +GET books/_search +{ + "query": { + "match_phrase": { + "suggestions": "four" + } + } +} +``` + +响应: + +```json +{ + "took" : 2, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 0.2876821, + "hits" : [ + { + "_index" : "books", + "_type" : "_doc", + "_id" : "1", + "_score" : 0.2876821, + "_source" : { + "suggestions" : "one two three four" + } + } + ] + } +} +``` + +## 参数 + +下表列出了 search-as-you-type 字段类型接受的参数。所有参数均为可选。 + +参数 | 描述 +:--- | :--- +`analyzer` | 用于该字段的分析器(Analyzer)。默认情况下,该分析器同时用于索引时和搜索时。如需在搜索时覆盖它,请设置 `search_analyzer` 参数。默认值为 `standard` 分析器,它使用基于语法的分词,并基于 [Unicode Text Segmentation](https://unicode.org/reports/tr29/) 算法。作用于根字段和子字段。 +`index` | 一个布尔值,指定该字段是否可搜索。默认值为 `true`。作用于根字段和子字段。 +`index_options` | 指定为搜索和高亮而在索引中存储的信息。有效值:`docs`(仅文档编号)、`freqs`(文档编号和词频)、`positions`(文档编号、词频和词项位置)、`offsets`(文档编号、词频、词项位置以及起止字符偏移量)。默认值为 `positions`。作用于根字段和子字段。 +`max_shingle_size` | 一个整数,指定 n-gram 的最大长度。有效值的范围为 [2, 4]。所创建的 n-gram 范围为 [2, `max_shingle_size`]。默认值为 3,即创建 2-gram 和 3-gram。较大的 `max_shingle_size` 值更适合更具体的查询,但会使索引更大。 +`norms` | 一个布尔值,指定计算相关性评分(Relevance Score)时是否使用字段长度。作用于根字段和 n-gram 子字段(默认值为 `false`)。不作用于前缀子字段(前缀子字段中 `norms` 为 `false`)。 +`search_analyzer` | 搜索时使用的分析器。默认值为 `analyzer` 参数中指定的分析器。作用于根字段和子字段。 +`search_quote_analyzer` | 搜索短语时使用的分析器。默认值为 `analyzer` 参数中指定的分析器。作用于根字段和子字段。 +`similarity` | 用于计算相关性评分的排名算法。默认值为 `BM25`。作用于根字段和子字段。 +`store` | 一个布尔值,指定是否存储该字段值,以便能够独立于 _source 字段单独检索。默认值为 `false`。仅作用于根字段。 +[`term_vector`](/field-types/supported-field-types/text#term-vector-parameter) | 一个布尔值,指定是否存储该字段的词项向量。默认值为 `no`。作用于根字段和 n-gram 子字段。不作用于前缀子字段。 diff --git a/i18n/zh/field-types/supported-field-types/string.md b/i18n/zh/field-types/supported-field-types/string.md new file mode 100644 index 00000000..6dd114a4 --- /dev/null +++ b/i18n/zh/field-types/supported-field-types/string.md @@ -0,0 +1,14 @@ +--- +title: 字符串字段类型 +--- + +# 字符串字段类型 + +字符串字段类型包含文本值或由文本派生的值。下表列出了 OpenSearch 支持的所有字符串字段类型。 + +字段数据类型 | 描述 +:--- | :--- +[`keyword`](/field-types/supported-field-types/keyword) | 不经过分析的字符串。适用于精确值搜索。 +[`text`](/field-types/supported-field-types/text) | 经过分析的字符串。适用于全文搜索。 +[`match_only_text`](/field-types/supported-field-types/match-only-text) | `text` 字段的空间优化版本。 +[`token_count`](/field-types/supported-field-types/token-count) | 统计字符串中的词元(Token)数量。 diff --git a/i18n/zh/field-types/supported-field-types/text.md b/i18n/zh/field-types/supported-field-types/text.md new file mode 100644 index 00000000..1d8397fd --- /dev/null +++ b/i18n/zh/field-types/supported-field-types/text.md @@ -0,0 +1,161 @@ +--- +title: Text +--- + +# Text 字段类型 + +`text` 字段类型包含一个经过分析的字符串。由于它支持部分匹配,因此用于全文搜索。对多个词项的搜索可以只匹配其中的一部分。根据所用分析器(Analyzer)的不同,结果可以不区分大小写、经过词干提取、去除停用词、应用同义词等。 + +::: info 注意 +如果需要将字段用于精确值搜索,请将其映射为 [`keyword`](/field-types/supported-field-types/keyword)。 +::: + +::: info 注意 +[`match_only_text`](/field-types/supported-field-types/match-only-text) 字段是 `text` 字段的空间优化版本。如果不需要查询短语或使用位置查询,请将字段映射为 `match_only_text` 而不是 `text`。位置查询是指词项在短语中的位置很重要的查询,例如 interval 查询或 span 查询。 +::: + +## 示例 + +创建一个包含 text 字段的映射(Mapping): + +```json +PUT movies +{ + "mappings" : { + "properties" : { + "title" : { + "type" : "text" + } + } + } +} +``` + +## 参数 + +下表列出了 text 字段类型接受的参数。所有参数均为可选。 + +参数 | 描述 +:--- | :--- +`analyzer` | 用于该字段的分析器。默认情况下,该分析器同时用于索引时和搜索时。如需在搜索时覆盖它,请设置 `search_analyzer` 参数。默认值为 `standard` 分析器,它使用基于语法的分词,并基于 [Unicode Text Segmentation](https://unicode.org/reports/tr29/) 算法。 +`boost` | 一个浮点值,指定该字段在相关性评分(Relevance Score)中的权重。大于 1.0 的值会提高该字段的相关性,介于 0.0 和 1.0 之间的值会降低该字段的相关性。默认值为 1.0。 +`eager_global_ordinals` | 指定是否在刷新时预先加载全局序数(global ordinals)。如果该字段经常用于聚合(Aggregation),应将此参数设置为 `true`。默认值为 `false`。 +`fielddata` | 一个布尔值,指定是否可以访问该字段经过分析的词元(Token),以用于排序、聚合和脚本。默认值为 `false`。 +`fielddata_frequency_filter` | 一个 JSON 对象,指定只将文档频率介于 `min` 和 `max` 值之间(以绝对数值或百分比表示)的分析后词元加载到内存中。频率按段计算。参数:`min`、`max`、`min_segment_size`。默认加载所有分析后的词元。 +`fields` | 如需以多种方式索引同一个字符串(例如同时作为 keyword 和 text),请提供 fields 参数。可以指定字段的一个版本用于搜索,另一个版本用于排序和聚合。 +`index` | 一个布尔值,指定该字段是否可搜索。默认值为 `true`。 +`index_options` | 指定为搜索和高亮而在索引中存储的信息。有效值:`docs`(仅文档编号)、`freqs`(文档编号和词频)、`positions`(文档编号、词频和词项位置)、`offsets`(文档编号、词频、词项位置以及起止字符偏移量)。默认值为 `positions`。 +`index_phrases` | 一个布尔值,指定是否单独索引 2-gram。2-gram 是该字段字符串中两个连续单词的组合。这样可以加快不带 slop 的精确短语查询,但会使索引更大。在不去除停用词时效果最佳。默认值为 `false`。 +`index_prefixes` | 一个 JSON 对象,指定单独索引词项前缀。前缀的字符数介于 `min_chars` 和 `max_chars` 之间(含边界)。这样可以加快前缀搜索,但会使索引更大。可选参数:`min_chars`、`max_chars`。`min_chars` 默认值为 2,`max_chars` 默认值为 5。 +`meta` | 接受该字段的元数据。 +`norms` | 一个布尔值,指定计算相关性评分时是否使用字段长度。默认值为 `false`。 +`position_increment_gap` | text 字段在分析时会被分配位置。如果字段包含一个字符串数组,并且这些位置是连续的,就可能导致跨不同数组元素的匹配。为防止这种情况,会在相邻的数组元素之间插入一个人为的间隔。可以通过指定整数 `position_increment_gap` 来更改该间隔。注意:如果 `slop` 大于 `position_element_gap`,则可能出现跨不同数组元素的匹配。默认值为 100。 +`similarity` | 用于计算相关性评分的排名算法。默认值为 `BM25`。 +[`term_vector`](#term-vector-parameter) | 一个布尔值,指定是否存储该字段的词项向量。默认值为 `no`。 + +## 词项向量参数 + +词项向量在分析过程中生成,它包含: +- 词项列表。 +- 每个词项的序数位置。 +- 搜索字符串在字段中的起止字符偏移量。 +- 载荷(payload,如果有)。每个词项都可以关联与该词项位置相关的自定义二进制数据。 + +`term_vector` 字段包含一个 JSON 对象,接受以下参数: + +参数 | 存储的值 +:--- | :--- +`no` | 无。这是默认值。 +`yes` | 字段中的词项。 +`with_offsets` | 词项和字符偏移量。 +`with_positions_offsets` | 词项、位置和字符偏移量。 +`with_positions_offsets_payloads` | 词项、位置、字符偏移量和载荷。 +`with_positions` | 词项和位置。 +`with_positions_payloads` | 词项、位置和载荷。 + +::: tip 提示 +存储位置对邻近查询很有用,存储字符偏移量对高亮很有用。 +::: + +### 词项向量参数示例 + +创建一个包含 text 字段的映射,并在词项向量中存储字符偏移量: + +```json +PUT testindex +{ + "mappings" : { + "properties" : { + "dob" : { + "type" : "text", + "term_vector": "with_positions_offsets" + } + } + } +} +``` + +索引一个包含 text 字段的文档(Document): + +```json +PUT testindex/_doc/1 +{ + "dob" : "The patient's date of birth." +} +``` + +查询 "date of birth",并在原始字段中将其高亮: + +```json +GET testindex/_search +{ + "query": { + "match": { + "text": "date of birth" + } + }, + "highlight": { + "fields": { + "text": {} + } + } +} +``` + +响应中 "date of birth" 这几个词被高亮显示: + +```json +{ + "took" : 854, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 0.8630463, + "hits" : [ + { + "_index" : "testindex", + "_type" : "_doc", + "_id" : "1", + "_score" : 0.8630463, + "_source" : { + "text" : "The patient's date of birth." + }, + "highlight" : { + "text" : [ + "The patient's date of birth." + ] + } + } + ] + } +} +``` diff --git a/i18n/zh/field-types/supported-field-types/token-count.md b/i18n/zh/field-types/supported-field-types/token-count.md new file mode 100644 index 00000000..5144d0ae --- /dev/null +++ b/i18n/zh/field-types/supported-field-types/token-count.md @@ -0,0 +1,109 @@ +--- +title: 词元计数 +--- + +# Token count 字段类型 + +token count 字段类型存储字符串中经过分析的词元(Token)数量。 + +## 示例 + +创建一个包含 token count 字段的映射(Mapping): + +```json +PUT testindex +{ + "mappings": { + "properties": { + "sentence": { + "type": "text", + "fields": { + "num_words": { + "type": "token_count", + "analyzer": "english" + } + } + } + } + } +} +``` + +索引三个包含 text 字段的文档(Document): + +```json +PUT testindex/_doc/1 +{ "sentence": "To be, or not to be: that is the question." } +``` + +```json +PUT testindex/_doc/2 +{ "sentence": "All the world’s a stage, and all the men and women are merely players." } +``` + +```json +PUT testindex/_doc/3 +{ "sentence": "Now is the winter of our discontent." } +``` + +搜索单词数少于 10 个的句子: + +```json +GET testindex/_search +{ + "query": { + "range": { + "sentence.num_words": { + "lt": 10 + } + } + } +} +``` + +响应中包含一个匹配的句子: + +```json +{ + "took" : 8, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "testindex", + "_type" : "_doc", + "_id" : "3", + "_score" : 1.0, + "_source" : { + "sentence" : "Now is the winter of our discontent." + } + } + ] + } +} +``` + +## 参数 + +下表列出了 token count 字段类型接受的参数。`analyzer` 参数为必需参数,其他参数均为可选。 + +参数 | 描述 +:--- | :--- +`analyzer` | 用于该字段的分析器(Analyzer)。为获得最佳性能,请指定不带词元过滤器(Token Filter)的分析器。必需。 +`boost` | 一个浮点值,指定该字段在相关性评分(Relevance Score)中的权重。大于 1.0 的值会提高该字段的相关性,介于 0.0 和 1.0 之间的值会降低该字段的相关性。默认值为 1.0。 +`doc_values` | 一个布尔值,指定是否将该字段存储到磁盘上,以便用于聚合、排序或脚本。默认值为 `false`。 +`enable_position_increments` | 一个布尔值,指定是否计入位置增量。为避免去除停用词,请将该字段设置为 `false`。默认值为 `true`。 +`index` | 一个布尔值,指定该字段是否可搜索。默认值为 `true`。 +[`null_value`](/field-types/supported-field-types/#null-value) | 用于替代 `null` 的值,必须与字段类型相同。如果未指定此参数,当字段值为 `null` 时,该字段被视为缺失。默认值为 `null`。 +`store` | 一个布尔值,指定是否存储该字段值,以便能够独立于 _source 字段单独检索。默认值为 `false`。 diff --git a/i18n/zh/field-types/supported-field-types/unsigned-long.md b/i18n/zh/field-types/supported-field-types/unsigned-long.md new file mode 100644 index 00000000..4105ba32 --- /dev/null +++ b/i18n/zh/field-types/supported-field-types/unsigned-long.md @@ -0,0 +1,150 @@ +--- +title: 无符号长整型 +--- + +# Unsigned long 字段类型 + +`unsigned_long` 字段类型是一种数值字段类型,表示无符号 64 位整数,最小值为 0,最大值为 264 − 1。在下面的示例中,`counter` 被映射为 `unsigned_long` 字段: + +```json +PUT testindex +{ + "mappings" : { + "properties" : { + "counter" : { + "type" : "unsigned_long" + } + } + } +} +``` + +## 索引 + +要索引一个包含 `unsigned_long` 值的文档(Document),请使用以下请求: + +```json +PUT testindex/_doc/1 +{ + "counter" : 10223372036854775807 +} +``` + +也可以按如下方式使用 [Bulk API](/api-reference/document-apis/bulk): + +```json +POST _bulk +{ "index": { "_index": "testindex", "_id": "1" } } +{ "counter": 10223372036854775807 } +``` + +::: info 注意 +如果 `unsigned_long` 类型字段的 `store` 参数设置为 `true`(即该字段是存储字段),它将以字符串形式存储和返回。`unsigned_long` 值不支持小数部分,因此如果提供了小数部分,它会被截断。 +::: + +## 查询 + +`unsigned_long` 字段支持其他数值类型所支持的大多数查询(Query)。例如,可以对 `unsigned_long` 字段使用 term 查询: + +```json +POST _search +{ + "query": { + "term": { + "counter": { + "value": 10223372036854775807 + } + } + } +} +``` + +也可以使用 range 查询: + +```json +POST _search +{ + "query": { + "range": { + "counter": { + "gte": 10223372036854775807 + } + } + } +} +``` + +## 排序 + +可以对 `unsigned_long` 字段使用 `sort` 值对搜索结果进行排序,例如: + +```json +POST _search +{ + "sort" : [ + { + "counter" : { + "order" : "asc" + } + } + ], + "query": { + "range": { + "counter": { + "gte": 10223372036854775807 + } + } + } +} +``` + +::: danger 警告 +`unsigned_long` 字段不能用作索引排序字段(即 `sort.field` 索引设置中的字段)。 +::: + +## 聚合 + +与其他数值字段一样,`unsigned_long` 字段支持聚合(Aggregation)。对于 `terms` 和 `multi_terms` 聚合,`unsigned_long` 值按原样使用;而对于其他类型的聚合,这些值会被转换为 `double` 类型(可能会损失精度)。以下是 `terms` 聚合的示例: + +```json +POST _search +{ + "query": { + "match_all": {} + }, + "aggs": { + "counters": { + "terms": { + "field": "counter" + } + } + } +} +``` + +## 脚本 + +在脚本中,`unsigned_long` 字段以 `BigInteger` 类的实例形式返回: + +```json +POST _search +{ + "query": { + "bool": { + "filter": { + "script": { + "script": "BigInteger amount = doc['counter'].value; return amount.compareTo(BigInteger.ZERO) > 0;" + } + } + } + } +} +``` + +## 限制 + +请注意 `unsigned_long` 字段类型的以下限制: + +- 当对不同数值类型执行聚合,且其中一种类型为 `unsigned_long` 时,值会被转换为 `double` 类型并使用 `double` 运算,很可能会损失精度。 + +- `unsigned_long` 字段不能用作索引排序字段(即 `sort.field` 索引设置中的字段)。当对多个索引执行搜索,且结果按某个字段排序,而该字段在至少一个索引中为 `unsigned_long` 类型、在其他索引中为其他数值类型时,此限制同样适用。 diff --git a/i18n/zh/field-types/supported-field-types/xy-point.md b/i18n/zh/field-types/supported-field-types/xy-point.md new file mode 100644 index 00000000..28028446 --- /dev/null +++ b/i18n/zh/field-types/supported-field-types/xy-point.md @@ -0,0 +1,93 @@ +--- +title: xy point +--- + +# xy point 字段类型 + +xy point 字段类型包含二维笛卡尔坐标系中的一个点,由 x 和 y 坐标指定。它基于 Lucene 的 [XYPoint](https://lucene.apache.org/core/9_3_0/core/org/apache/lucene/geo/XYPoint.html) 字段类型。xy point 字段类型与 [geopoint](/field-types/supported-field-types/geo-point) 字段类型类似,但没有 geopoint 的取值范围限制。xy point 的坐标是单精度浮点值。有关浮点值的范围和精度,请参阅[数值字段类型](/field-types/supported-field-types/numeric)。 + +## 示例 + +创建一个包含 xy point 字段类型的映射(Mapping): + +```json +PUT testindex1 +{ + "mappings": { + "properties": { + "point": { + "type": "xy_point" + } + } + } +} +``` + +## 格式 + +xy point 可以按以下格式进行索引: + +- 包含 x 和 y 坐标的对象 + +```json +PUT testindex1/_doc/1 +{ + "point": { + "x": 0.5, + "y": 4.5 + } +} +``` + +- "`x`, `y`" 格式的字符串 + +```json +PUT testindex1/_doc/2 +{ + "point": "0.5, 4.5" +} +``` + +- [`x`, `y`] 格式的数组 + +```json +PUT testindex1/_doc/3 +{ + "point": [0.5, 4.5] +} +``` + +- "POINT(`x` `y`)" 格式的[熟知文本(Well-known Text,WKT)](https://docs.opengeospatial.org/is/12-063r5/12-063r5.html) POINT + +```json +PUT testindex1/_doc/4 +{ + "point": "POINT (0.5 4.5)" +} +``` + +- GeoJSON 格式 + +```json +PUT testindex1/_doc/5 +{ + "point" : { + "type" : "Point", + "coordinates" : [0.5, 4.5] + } +} +``` + +::: info 注意 +在所有 xy point 格式中,坐标都必须按 `x, y` 的顺序指定。 +::: + +## 参数 + +下表列出了 xy point 字段类型接受的参数。所有参数均为可选。 + +参数 | 描述 +:--- | :--- +`ignore_malformed` | 一个布尔值,指定是否忽略格式错误的值而不抛出异常。默认值为 `false`。 +`ignore_z_value` | 仅适用于具有三个坐标的点。如果 `ignore_z_value` 为 `true`,第三个坐标不会被索引,但仍会存储在 _source 字段中。如果 `ignore_z_value` 为 `false`,则会抛出异常。 +[`null_value`](/field-types/supported-field-types/#null-value) | 用于替代 `null` 的值。该值必须与字段类型相同。如果未指定此参数,当字段值为 `null` 时,该字段被视为缺失。默认值为 `null`。 diff --git a/i18n/zh/field-types/supported-field-types/xy-shape.md b/i18n/zh/field-types/supported-field-types/xy-shape.md new file mode 100644 index 00000000..6af5d388 --- /dev/null +++ b/i18n/zh/field-types/supported-field-types/xy-shape.md @@ -0,0 +1,378 @@ +--- +title: xy shape +--- + +# xy shape 字段类型 + +xy shape 字段类型包含一个形状,例如多边形或 xy 点的集合。它基于 Lucene 的 [XYShape](https://lucene.apache.org/core/9_3_0/core/org/apache/lucene/document/XYShape.html) 字段类型。为了索引 xy shape,OpenSearch 会将形状剖分为三角网格,并将每个三角形存储在 BKD 树(一组平衡的 k 维树)中。这可以提供 10-7 十进制度的精度,代表近乎完美的空间分辨率。 + +xy shape 字段类型与 [geoshape](/field-types/supported-field-types/geo-shape) 字段类型类似,但它表示的是笛卡尔平面上的形状,而笛卡尔平面并不基于地固地球参考系。xy shape 的坐标是单精度浮点值。有关浮点值的范围和精度,请参阅[数值字段类型](/field-types/supported-field-types/numeric)。 + +## 示例 + +创建一个包含 xy shape 字段类型的映射(Mapping): + +```json +PUT testindex +{ + "mappings": { + "properties": { + "location": { + "type": "xy_shape" + } + } + } +} +``` + +## 格式 + +xy shape 可以按以下格式进行索引: + +- [GeoJSON](https://geojson.org/) +- [熟知文本(Well-known Text,WKT)](https://docs.opengeospatial.org/is/12-063r5/12-063r5.html) + +::: info 注意 +无论是 GeoJSON 还是 WKT,坐标数组中的坐标都必须按 `x, y` 的顺序指定。 +::: + +## xy shape 类型 + +下表介绍了可用的 xy shape 类型及其与 GeoJSON 和 WKT 类型的对应关系。 + +OpenSearch 类型 | GeoJSON 类型 | WKT 类型 | 描述 +:--- | :--- | :--- | :--- +[`point`](#point) | Point | POINT | 由 x 和 y 坐标指定的地理点。 +[`linestring`](#linestring) | LineString | LINESTRING | 由两个或更多点指定的线。可以是一条直线,也可以是由相连线段组成的路径。 +[`polygon`](#polygon) | Polygon | POLYGON | 由坐标形式的顶点列表指定的多边形。多边形必须闭合,即最后一个点必须与第一个点相同。因此,创建一个 n 边形需要 n+1 个顶点。顶点的最少数量为四个,即创建一个三角形。 +[`multipoint`](#multipoint) | MultiPoint | MULTIPOINT | 一组互不相连但彼此相关的离散点构成的数组。 +[`multilinestring`](#multilinestring) | MultiLineString | MULTILINESTRING | linestring 数组。 +[`multipolygon`](#multipolygon) | MultiPolygon | MULTIPOLYGON | 多边形数组。 +[`geometrycollection`](#geometry-collection) | GeometryCollection | GEOMETRYCOLLECTION | 可以包含不同类型的 xy shape 的集合。 +[`envelope`](#envelope) | N/A | BBOX | 由左上角和右下角顶点指定的边界矩形。 + +## Point + +point 由一对坐标指定。 + +以 GeoJSON 格式索引一个 point: + +```json +PUT testindex/_doc/1 +{ + "location" : { + "type" : "point", + "coordinates" : [0.5, 4.5] + } +} +``` + +以 WKT 格式索引一个 point: + +```json +PUT testindex/_doc/1 +{ + "location" : "POINT (0.5 4.5)" +} +``` + +## Linestring + +linestring 是由两个或更多点指定的线。如果这些点共线,则 linestring 是一条直线;否则,linestring 表示由线段组成的路径。 + +以 GeoJSON 格式索引一个 linestring: + +```json +PUT testindex/_doc/2 +{ + "location" : { + "type" : "linestring", + "coordinates" : [[0.5, 4.5], [-1.5, 2.3]] + } +} +``` + +以 WKT 格式索引一个 linestring: + +```json +PUT testindex/_doc/2 +{ + "location" : "LINESTRING (0.5 4.5, -1.5 2.3)" +} +``` + +## Polygon + +polygon 由坐标形式的顶点列表指定。多边形必须闭合,即最后一个点必须与第一个点相同。在下面的示例中,使用四个点创建了一个三角形。 + +::: info 注意 +GeoJSON 要求按逆时针顺序列出多边形的顶点,WKT 则不要求顶点的特定顺序。 +::: + +以 GeoJSON 格式索引一个多边形(三角形): + +```json +PUT testindex/_doc/3 +{ + "location" : { + "type" : "polygon", + "coordinates" : [ + [[0.5, 4.5], + [2.5, 6.0], + [1.5, 2.0], + [0.5, 4.5]] + ] + } +} +``` + +以 WKT 格式索引一个多边形(三角形): + +```json +PUT testindex/_doc/3 +{ + "location" : "POLYGON ((0.5 4.5, 2.5 6.0, 1.5 2.0, 0.5 4.5))" +} +``` + +多边形内部可以有洞。在这种情况下,`coordinates` 字段将包含多个数组。第一个数组表示外部多边形,之后的每个数组各表示一个洞。洞以多边形表示,并以坐标数组的形式指定。 + +::: info 注意 +GeoJSON 要求按逆时针顺序列出多边形的顶点,并按顺时针顺序列出洞的顶点。WKT 则不要求顶点的特定顺序。 +::: + +以 GeoJSON 格式索引一个带有三角形洞的多边形(三角形): + +```json +PUT testindex/_doc/4 +{ + "location" : { + "type" : "polygon", + "coordinates" : [ + [[0.5, 4.5], + [2.5, 6.0], + [1.5, 2.0], + [0.5, 4.5]], + + [[1.0, 4.5], + [1.5, 4.5], + [1.5, 4.0], + [1.0, 4.5]] + ] + } +} +``` + +以 WKT 格式索引一个带有三角形洞的多边形(三角形): + +```json +PUT testindex/_doc/4 +{ + "location" : "POLYGON ((0.5 4.5, 2.5 6.0, 1.5 2.0, 0.5 4.5), (1.0 4.5, 1.5 4.5, 1.5 4.0, 1.0 4.5))" +} +``` + +默认情况下,多边形的顶点按逆时针顺序遍历。可以在映射时定义 [`orientation`](#parameters) 参数来指定顶点的遍历顺序: + +```json +PUT testindex +{ + "mappings": { + "properties": { + "location": { + "type": "xy_shape", + "orientation" : "left" + } + } + } +} +``` + +之后索引的文档(Document)可以覆盖 `orientation` 设置: + +```json +PUT testindex/_doc/3 +{ + "location" : { + "type" : "polygon", + "orientation" : "cw", + "coordinates" : [ + [[0.5, 4.5], + [2.5, 6.0], + [1.5, 2.0], + [0.5, 4.5]] + ] + } +} +``` + +## Multipoint + +multipoint 是一组互不相连但彼此相关的离散点构成的数组。 + +以 GeoJSON 格式索引一个 multipoint: + +```json +PUT testindex/_doc/6 +{ + "location" : { + "type" : "multipoint", + "coordinates" : [ + [0.5, 4.5], + [2.5, 6.0] + ] + } +} +``` + +以 WKT 格式索引一个 multipoint: + +```json +PUT testindex/_doc/6 +{ + "location" : "MULTIPOINT (0.5 4.5, 2.5 6.0)" +} +``` + +## Multilinestring + +multilinestring 是 linestring 数组。 + +以 GeoJSON 格式索引一个 multilinestring: + +```json +PUT testindex/_doc/2 +{ + "location" : { + "type" : "multilinestring", + "coordinates" : [ + [[0.5, 4.5], [2.5, 6.0]], + [[1.5, 2.0], [3.5, 3.5]] + ] + } +} +``` + +以 WKT 格式索引一个 linestring: + +```json +PUT testindex/_doc/2 +{ + "location" : "MULTILINESTRING ((0.5 4.5, 2.5 6.0), (1.5 2.0, 3.5 3.5))" +} +``` + +## Multipolygon + +multipolygon 是多边形数组。在本示例中,第一个多边形包含一个洞,第二个则没有。 + +以 GeoJSON 格式索引一个 multipolygon: + +```json +PUT testindex/_doc/4 +{ + "location" : { + "type" : "multipolygon", + "coordinates" : [ + [ + [[0.5, 4.5], + [2.5, 6.0], + [1.5, 2.0], + [0.5, 4.5]], + + [[1.0, 4.5], + [1.5, 4.5], + [1.5, 4.0], + [1.0, 4.5]] + ], + [ + [[2.0, 0.0], + [1.0, 2.0], + [3.0, 1.0], + [2.0, 0.0]] + ] + ] + } +} +``` + +以 WKT 格式索引一个 multipolygon: + +```json +PUT testindex/_doc/4 +{ + "location" : "MULTIPOLYGON (((0.5 4.5, 2.5 6.0, 1.5 2.0, 0.5 4.5), (1.0 4.5, 1.5 4.5, 1.5 4.0, 1.0 4.5)), ((2.0 0.0, 1.0 2.0, 3.0 1.0, 2.0 0.0)))" +} +``` + +## Geometry collection + +geometry collection 是可以包含不同类型的 xy shape 的集合。 + +以 GeoJSON 格式索引一个 geometry collection: + +```json +PUT testindex/_doc/7 +{ + "location" : { + "type": "geometrycollection", + "geometries": [ + { + "type": "point", + "coordinates": [0.5, 4.5] + }, + { + "type": "linestring", + "coordinates": [[2.5, 6.0], [1.5, 2.0]] + } + ] + } +} +``` + +以 WKT 格式索引一个 geometry collection: + +```json +PUT testindex/_doc/7 +{ + "location" : "GEOMETRYCOLLECTION (POINT (0.5 4.5), LINESTRING(2.5 6.0, 1.5 2.0))" +} +``` + +## Envelope + +envelope 是由左上角和右下角顶点指定的边界矩形。其 GeoJSON 格式为 `[[minX, maxY], [maxX, minY]]`。 + +以 GeoJSON 格式索引一个 envelope: + +```json +PUT testindex/_doc/2 +{ + "location" : { + "type" : "envelope", + "coordinates" : [[3.0, 2.0], [6.0, 0.0]] + } +} +``` + +在 WKT 格式中,请使用 `BBOX (minX, maxY, maxX, minY)`。 + +以 WKT BBOX 格式索引一个 envelope: + +```json +PUT testindex/_doc/8 +{ + "location" : "BBOX (3.0, 2.0, 6.0, 0.0)" +} +``` + +## 参数 + +下表列出了 xy shape 字段类型接受的参数。所有参数均为可选。 + +参数 | 描述 +:--- | :--- +`coerce` | 一个布尔值,指定是否自动闭合未闭合的线性环。默认值为 `false`。 +`ignore_malformed` | 一个布尔值,指定是否忽略格式错误的 GeoJSON 或 WKT xy shape 而不抛出异常。默认值为 `false`(xy shape 格式错误时抛出异常)。 +`ignore_z_value` | 仅适用于具有三个坐标的点。如果 `ignore_z_value` 为 `true`,第三个坐标不会被索引,但仍会存储在 _source 字段中。如果 `ignore_z_value` 为 `false`,则会抛出异常。默认值为 `true`。 +`orientation` | 指定 xy shape 坐标列表中顶点的遍历顺序。`orientation` 可取以下值:
1. RIGHT:逆时针。使用以下任一字符串(大小写均可)指定 RIGHT 方向:`right`、`counterclockwise`、`ccw`。
2. LEFT:顺时针。使用以下任一字符串(大小写均可)指定 LEFT 方向:`left`、`clockwise`、`cw`。该值可以被单个文档覆盖。
默认值为 `RIGHT`。 diff --git a/i18n/zh/field-types/supported-field-types/xy.md b/i18n/zh/field-types/supported-field-types/xy.md new file mode 100644 index 00000000..562ac4bf --- /dev/null +++ b/i18n/zh/field-types/supported-field-types/xy.md @@ -0,0 +1,22 @@ +--- +title: 笛卡尔字段类型 +--- + +# 笛卡尔字段类型 + +笛卡尔字段类型便于在二维笛卡尔坐标系中索引和搜索点与形状。笛卡尔字段类型与[地理](/field-types/supported-field-types/geographic)字段类型类似,区别在于它们表示的是笛卡尔平面上的点和形状,而笛卡尔平面并不基于地固地球参考系。在平面上计算距离比在球面上计算距离更高效,因此笛卡尔字段类型的距离排序速度更快。 + +笛卡尔字段类型非常适合虚拟现实、计算机辅助设计(CAD)以及游乐园和体育场馆地图绘制等空间应用。 + +笛卡尔字段类型的坐标是单精度浮点值。有关浮点值的范围和精度,请参阅[数值字段类型](/field-types/supported-field-types/numeric)。 + +下表列出了 OpenSearch 支持的所有笛卡尔字段类型。 + +字段数据类型 | 描述 +:--- | :--- +[`xy_point`](/field-types/supported-field-types/xy-point) | 二维笛卡尔坐标系中的一个点,由 x 和 y 坐标指定。 +[`xy_shape`](/field-types/supported-field-types/xy-shape) | 二维笛卡尔坐标系中的一个形状,例如多边形或 xy 点的集合。 + +::: info 注意 +目前,OpenSearch 支持索引和搜索笛卡尔字段类型,但不支持对笛卡尔字段类型进行聚合(Aggregation)。如果希望实现聚合功能,请提交 [GitHub issue](https://github.com/opensearch-project/geospatial)。 +::: diff --git a/i18n/zh/query-dsl/compound/bool.md b/i18n/zh/query-dsl/compound/bool.md new file mode 100644 index 00000000..833ad8d7 --- /dev/null +++ b/i18n/zh/query-dsl/compound/bool.md @@ -0,0 +1,283 @@ +--- +title: 布尔查询 +--- + +# 布尔查询 + +布尔(`bool`)查询(Query)可以将多个查询子句组合成一个高级查询。这些子句通过布尔逻辑组合,用于查找要在结果中返回的匹配文档(Document)。 + +在 `bool` 查询中可以使用以下查询子句: + +子句 | 行为 +:--- | :--- +`must` | 逻辑 `and` 运算符。结果必须匹配该子句中的所有查询。 +`must_not` | 逻辑 `not` 运算符。所有匹配项都会从结果中排除。 +`should` | 逻辑 `or` 运算符。结果必须至少匹配其中一个查询。匹配的 `should` 子句越多,文档的相关性评分(Relevance Score)越高。可以使用 [`minimum_should_match`](/query-dsl/minimum-should-match) 参数设置必须匹配的最少查询数。如果查询包含 `must` 或 `filter` 子句,则 `minimum_should_match` 的默认值为 0;否则默认值为 1。 +`filter` | 逻辑 `and` 运算符,在执行查询之前先应用,用于缩小数据集。filter 子句中的查询是一个是或否的选择:如果文档匹配该查询,就会在结果中返回;否则不返回。filter 查询的结果通常会被缓存,以便更快地返回。可以使用 filter 查询根据精确匹配、范围、日期或数字来过滤结果。 + +布尔查询的结构如下: + +```json +GET _search +{ + "query": { + "bool": { + "must": [ + {} + ], + "must_not": [ + {} + ], + "should": [ + {} + ], + "filter": {} + } + } +} +``` + +例如,假设你已将莎士比亚全集索引到 OpenSearch 集群中,现在想构造一个满足以下要求的查询: + +1. `text_entry` 字段必须包含单词 `love`,并且应当包含 `life` 或 `grace` 之一。 +2. `speaker` 字段不得包含 `ROMEO`。 +3. 将这些结果过滤为剧目 `Romeo and Juliet`,且不影响相关性评分。 + +这些要求可以组合成以下查询: + +```json +GET shakespeare/_search +{ + "query": { + "bool": { + "must": [ + { + "match": { + "text_entry": "love" + } + } + ], + "should": [ + { + "match": { + "text_entry": "life" + } + }, + { + "match": { + "text_entry": "grace" + } + } + ], + "minimum_should_match": 1, + "must_not": [ + { + "match": { + "speaker": "ROMEO" + } + } + ], + "filter": { + "term": { + "play_name": "Romeo and Juliet" + } + } + } + } +} +``` + +响应中包含匹配的文档: + +```json +{ + "took": 12, + "timed_out": false, + "_shards": { + "total": 4, + "successful": 4, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 11.356054, + "hits": [ + { + "_index": "shakespeare", + "_id": "88020", + "_score": 11.356054, + "_source": { + "type": "line", + "line_id": 88021, + "play_name": "Romeo and Juliet", + "speech_number": 19, + "line_number": "4.5.61", + "speaker": "PARIS", + "text_entry": "O love! O life! not life, but love in death!" + } + } + ] + } +} +``` + +如果想确定究竟是哪些子句产生了匹配结果,可以使用 `_name` 参数为每个查询命名。 +要添加 `_name` 参数,请将 `match` 查询中的字段名改为一个对象: + +```json +GET shakespeare/_search +{ + "query": { + "bool": { + "must": [ + { + "match": { + "text_entry": { + "query": "love", + "_name": "love-must" + } + } + } + ], + "should": [ + { + "match": { + "text_entry": { + "query": "life", + "_name": "life-should" + } + } + }, + { + "match": { + "text_entry": { + "query": "grace", + "_name": "grace-should" + } + } + } + ], + "minimum_should_match": 1, + "must_not": [ + { + "match": { + "speaker": { + "query": "ROMEO", + "_name": "ROMEO-must-not" + } + } + } + ], + "filter": { + "term": { + "play_name": "Romeo and Juliet" + } + } + } + } +} +``` + +OpenSearch 会返回一个 `matched_queries` 数组,列出与这些结果匹配的查询: + +```json +"matched_queries": [ + "love-must", + "life-should" +] +``` + +即使删除不在此列表中的查询,仍会得到完全相同的结果。 +通过检查匹配的是哪个 `should` 子句,可以更好地理解结果的相关性评分。 + +还可以通过嵌套 `bool` 查询来构造复杂的布尔表达式。 +例如,使用以下查询在剧目 `Romeo and Juliet` 中查找匹配 (`love` OR `hate`) AND (`life` OR `grace`) 的 `text_entry` 字段: + +```json +GET shakespeare/_search +{ + "query": { + "bool": { + "must": [ + { + "bool": { + "should": [ + { + "match": { + "text_entry": "love" + } + }, + { + "match": { + "text": "hate" + } + } + ] + } + }, + { + "bool": { + "should": [ + { + "match": { + "text_entry": "life" + } + }, + { + "match": { + "text": "grace" + } + } + ] + } + } + ], + "filter": { + "term": { + "play_name": "Romeo and Juliet" + } + } + } + } +} +``` + +响应中包含匹配的文档: + +```json +{ + "took": 10, + "timed_out": false, + "_shards": { + "total": 2, + "successful": 2, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": 1, + "max_score": 11.37006, + "hits": [ + { + "_index": "shakespeare", + "_type": "doc", + "_id": "88020", + "_score": 11.37006, + "_source": { + "type": "line", + "line_id": 88021, + "play_name": "Romeo and Juliet", + "speech_number": 19, + "line_number": "4.5.61", + "speaker": "PARIS", + "text_entry": "O love! O life! not life, but love in death!" + } + } + ] + } +} +``` diff --git a/i18n/zh/query-dsl/compound/boosting.md b/i18n/zh/query-dsl/compound/boosting.md new file mode 100644 index 00000000..14f016e2 --- /dev/null +++ b/i18n/zh/query-dsl/compound/boosting.md @@ -0,0 +1,153 @@ +--- +title: Boosting +--- + +# Boosting 查询 + +如果搜索单词 "pitcher",结果可能与棒球投手有关,也可能与盛装液体的水罐有关。如果是在棒球语境下搜索,可以使用 `must_not` 子句完全排除包含 "glass" 或 "water" 等单词的结果。但如果想保留这些结果、只是降低它们的相关性,则可以使用 `boosting` 查询(Query)。 + +`boosting` 查询返回匹配 `positive` 查询的文档(Document)。在这些文档中,同时匹配 `negative` 查询的文档会获得较低的相关性评分(Relevance Score)(其相关性评分会乘以负向权重提升(boost)系数)。 + +## 示例 + +假设有一个索引(Index),并按如下方式索引了两个文档: + +```json +PUT testindex/_doc/1 +{ + "article_name": "The greatest pitcher in baseball history" +} +``` + +```json +PUT testindex/_doc/2 +{ + "article_name": "The making of a glass pitcher" +} +``` + +使用以下 match 查询搜索包含单词 "pitcher" 的文档: + +```json +GET testindex/_search +{ + "query": { + "match": { + "article_name": "pitcher" + } + } +} +``` + +返回的两个文档具有相同的相关性评分: + +```json +{ + "took": 5, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.18232156, + "hits": [ + { + "_index": "testindex", + "_id": "1", + "_score": 0.18232156, + "_source": { + "article_name": "The greatest pitcher in baseball history" + } + }, + { + "_index": "testindex", + "_id": "2", + "_score": 0.18232156, + "_source": { + "article_name": "The making of a glass pitcher" + } + } + ] + } +} +``` + +现在使用以下 `boosting` 查询搜索包含单词 "pitcher" 的文档,但降低包含 "glass"、"crystal" 或 "water" 等单词的文档的排名: + +```json +GET testindex/_search +{ + "query": { + "boosting": { + "positive": { + "match": { + "article_name": "pitcher" + } + }, + "negative": { + "match": { + "article_name": "glass crystal water" + } + }, + "negative_boost": 0.1 + } + } +} +``` + +两个文档仍然都会返回,但包含单词 "glass" 的文档的相关性评分比上一种情况低 10 倍: + +```json +{ + "took": 13, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.18232156, + "hits": [ + { + "_index": "testindex", + "_id": "1", + "_score": 0.18232156, + "_source": { + "article_name": "The greatest pitcher in baseball history" + } + }, + { + "_index": "testindex", + "_id": "2", + "_score": 0.018232157, + "_source": { + "article_name": "The making of a glass pitcher" + } + } + ] + } +} +``` + +## 参数 + +下表列出了 `boosting` 查询支持的所有顶级参数。 + +参数 | 描述 +:--- | :--- +`positive` | 文档要在结果中返回所必须匹配的查询。必需。 +`negative` | 如果结果中的某个文档匹配该查询,则将其原始相关性评分(由 `positive` 查询产生)乘以 `negative_boost` 参数,以降低其相关性评分。必需。 +`negative_boost` | 一个介于 0 和 1.0 之间的浮点系数,原始相关性评分会乘以该系数,以降低匹配 `negative` 查询的文档的相关性。必需。 diff --git a/i18n/zh/query-dsl/compound/constant-score.md b/i18n/zh/query-dsl/compound/constant-score.md new file mode 100644 index 00000000..a4e1b2c4 --- /dev/null +++ b/i18n/zh/query-dsl/compound/constant-score.md @@ -0,0 +1,206 @@ +--- +title: 常量评分 +--- + +# 常量评分查询 + +如果需要返回包含某个单词的文档(Document),而不关心该单词出现的次数,可以使用 `constant_score` 查询(Query)。`constant_score` 查询包装一个 filter 查询,并为结果中的所有文档分配一个等于 `boost` 参数值的相关性评分(Relevance Score)。因此,所有返回的文档都具有相同的相关性评分,并且不考虑词频/逆文档频率(TF/IDF)。filter 查询不计算相关性评分。此外,OpenSearch 会缓存常用的 filter 查询以提升性能。 + +## 示例 + +使用以下查询返回 `shakespeare` 索引中包含单词 "Hamlet" 的文档: + +```json +GET shakespeare/_search +{ + "query": { + "constant_score": { + "filter": { + "match": { + "text_entry": "Hamlet" + } + }, + "boost": 1.2 + } + } +} +``` + +结果中的所有文档都被分配了 1.2 的相关性评分: + +
+ + 响应 + + +```json +{ + "took": 8, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 96, + "relation": "eq" + }, + "max_score": 1.2, + "hits": [ + { + "_index": "shakespeare", + "_id": "32535", + "_score": 1.2, + "_source": { + "type": "line", + "line_id": 32536, + "play_name": "Hamlet", + "speech_number": 48, + "line_number": "1.1.97", + "speaker": "HORATIO", + "text_entry": "Dared to the combat; in which our valiant Hamlet--" + } + }, + { + "_index": "shakespeare", + "_id": "32546", + "_score": 1.2, + "_source": { + "type": "line", + "line_id": 32547, + "play_name": "Hamlet", + "speech_number": 48, + "line_number": "1.1.108", + "speaker": "HORATIO", + "text_entry": "His fell to Hamlet. Now, sir, young Fortinbras," + } + }, + { + "_index": "shakespeare", + "_id": "32625", + "_score": 1.2, + "_source": { + "type": "line", + "line_id": 32626, + "play_name": "Hamlet", + "speech_number": 59, + "line_number": "1.1.184", + "speaker": "HORATIO", + "text_entry": "Unto young Hamlet; for, upon my life," + } + }, + { + "_index": "shakespeare", + "_id": "32633", + "_score": 1.2, + "_source": { + "type": "line", + "line_id": 32634, + "play_name": "Hamlet", + "speech_number": 60, + "line_number": "", + "speaker": "MARCELLUS", + "text_entry": "Enter KING CLAUDIUS, QUEEN GERTRUDE, HAMLET, POLONIUS, LAERTES, VOLTIMAND, CORNELIUS, Lords, and Attendants" + } + }, + { + "_index": "shakespeare", + "_id": "32634", + "_score": 1.2, + "_source": { + "type": "line", + "line_id": 32635, + "play_name": "Hamlet", + "speech_number": 1, + "line_number": "1.2.1", + "speaker": "KING CLAUDIUS", + "text_entry": "Though yet of Hamlet our dear brothers death" + } + }, + { + "_index": "shakespeare", + "_id": "32699", + "_score": 1.2, + "_source": { + "type": "line", + "line_id": 32700, + "play_name": "Hamlet", + "speech_number": 8, + "line_number": "1.2.65", + "speaker": "KING CLAUDIUS", + "text_entry": "But now, my cousin Hamlet, and my son,--" + } + }, + { + "_index": "shakespeare", + "_id": "32703", + "_score": 1.2, + "_source": { + "type": "line", + "line_id": 32704, + "play_name": "Hamlet", + "speech_number": 12, + "line_number": "1.2.69", + "speaker": "QUEEN GERTRUDE", + "text_entry": "Good Hamlet, cast thy nighted colour off," + } + }, + { + "_index": "shakespeare", + "_id": "32723", + "_score": 1.2, + "_source": { + "type": "line", + "line_id": 32724, + "play_name": "Hamlet", + "speech_number": 16, + "line_number": "1.2.89", + "speaker": "KING CLAUDIUS", + "text_entry": "Tis sweet and commendable in your nature, Hamlet," + } + }, + { + "_index": "shakespeare", + "_id": "32754", + "_score": 1.2, + "_source": { + "type": "line", + "line_id": 32755, + "play_name": "Hamlet", + "speech_number": 17, + "line_number": "1.2.120", + "speaker": "QUEEN GERTRUDE", + "text_entry": "Let not thy mother lose her prayers, Hamlet:" + } + }, + { + "_index": "shakespeare", + "_id": "32759", + "_score": 1.2, + "_source": { + "type": "line", + "line_id": 32760, + "play_name": "Hamlet", + "speech_number": 19, + "line_number": "1.2.125", + "speaker": "KING CLAUDIUS", + "text_entry": "This gentle and unforced accord of Hamlet" + } + } + ] + } +} +``` +
+ +## 参数 + +下表列出了 `constant_score `查询支持的所有顶级参数。 + +参数 | 描述 +:--- | :--- +`filter` | 文档要在结果中返回所必须匹配的 filter 查询。必需。 +`boost` | 一个浮点值,作为相关性评分分配给所有返回的文档。可选。默认值为 1.0。 diff --git a/i18n/zh/query-dsl/compound/disjunction-max.md b/i18n/zh/query-dsl/compound/disjunction-max.md new file mode 100644 index 00000000..dd259f50 --- /dev/null +++ b/i18n/zh/query-dsl/compound/disjunction-max.md @@ -0,0 +1,96 @@ +--- +title: 析取最大值 +--- + +# 析取最大值查询 + +析取最大值(`dis_max`)查询(Query)返回匹配一个或多个查询子句的任何文档(Document)。对于匹配多个查询子句的文档,其相关性评分(Relevance Score)取所有匹配查询子句中的最高相关性评分。 + +当返回文档的相关性评分相同时,可以使用 `tie_breaker` 参数为匹配多个查询子句的文档赋予更高的权重。 + +## 示例 + +假设有一个索引(Index),并按如下方式索引了两个文档: + +```json +PUT testindex1/_doc/1 +{ + "title": " The Top 10 Shakespeare Poems", + "description": "Top 10 sonnets of England's national poet and the Bard of Avon" +} +``` + +```json +PUT testindex1/_doc/2 +{ + "title": "Sonnets of the 16th Century", + "body": "The poems written by various 16-th century poets" +} +``` + +使用 `dis_max` 查询搜索包含 "Shakespeare poems" 这些单词的文档: + +```json +GET testindex1/_search +{ + "query": { + "dis_max": { + "queries": [ + { "match": { "title": "Shakespeare poems" }}, + { "match": { "body": "Shakespeare poems" }} + ] + } + } +} +``` + +响应中包含这两个文档: + +```json +{ + "took": 8, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1.3862942, + "hits": [ + { + "_index": "testindex1", + "_id": "1", + "_score": 1.3862942, + "_source": { + "title": " The Top 10 Shakespeare Poems", + "description": "Top 10 sonnets of England's national poet and the Bard of Avon" + } + }, + { + "_index": "testindex1", + "_id": "2", + "_score": 0.2876821, + "_source": { + "title": "Sonnets of the 16th Century", + "body": "The poems written by various 16-th century poets" + } + } + ] + } +} +``` + +## 参数 + +下表列出了 `dis_max` 查询支持的所有顶级参数。 + +参数 | 描述 +:--- | :--- +`queries` | 由一个或多个用于匹配文档的查询子句组成的数组。文档必须至少匹配一个查询子句才能在结果中返回。如果文档匹配多个查询子句,则其相关性评分取所有匹配查询子句中的最高相关性评分。必需。 +`tie_breaker` | 一个介于 0 和 1.0 之间的浮点系数,用于为匹配多个查询子句的文档赋予更高的权重。在这种情况下,文档的相关性评分按以下算法计算:取所有匹配查询子句中的最高相关性评分,将其他所有匹配子句的评分乘以 `tie_breaker` 值,然后将这些相关性评分相加并进行归一化。可选。默认值为 0(表示只计算最高评分)。 diff --git a/i18n/zh/query-dsl/compound/function-score.md b/i18n/zh/query-dsl/compound/function-score.md new file mode 100644 index 00000000..b9732b56 --- /dev/null +++ b/i18n/zh/query-dsl/compound/function-score.md @@ -0,0 +1,806 @@ +--- +title: 函数评分 +--- + +# 函数评分查询 + +如果需要改变结果中返回文档的相关性评分(Relevance Score),可以使用 `function_score` 查询(Query)。`function_score` 查询定义一个查询以及一个或多个函数,这些函数可以应用于全部结果或部分结果,以重新计算它们的相关性评分。 + +## 使用一个评分函数 + +`function_score` 查询最基本的示例是使用一个函数重新计算评分。以下查询使用 `weight` 函数将所有相关性评分翻倍。由于 `function_score` 中未指定 `query` 参数,该函数会应用于结果中的所有文档(Document): + +```json +GET shakespeare/_search +{ + "query": { + "function_score": { + "weight": "2" + } + } +} +``` + +## 将评分函数应用于部分文档 + +要将评分函数应用于部分文档,请在函数中提供一个查询: + +```json +GET shakespeare/_search +{ + "query": { + "function_score": { + "query": { + "match": { + "play_name": "Hamlet" + } + }, + "weight": "2" + } + } +} +``` + +## 支持的函数 + +`function_score` 查询类型支持以下函数: + +- 内置函数: + - `weight`:将文档评分乘以预定义的权重提升(boost)系数。 + - `random_score`:提供一个随机评分,该评分对同一用户保持一致,但对不同用户各不相同。 + - `field_value_factor`:使用指定文档字段的值重新计算评分。 + - 衰减函数(`gauss`、`exp` 和 `linear`):使用指定的衰减函数重新计算评分。 +- 自定义函数: + - `script_score`:使用脚本为文档评分。 + +## weight 函数 + +使用 `weight` 函数时,原始相关性评分会乘以 `weight` 的浮点值: + +```json +GET shakespeare/_search +{ + "query": { + "function_score": { + "weight": "2" + } + } +} +``` + +与 `boost` 值不同,`weight` 函数不会被归一化。 + +## random score 函数 + +`random_score` 函数提供一个随机评分,该评分对同一用户保持一致,但对不同用户各不相同。评分是 [0, 1) 范围内的浮点数。默认情况下,`random_score` 函数使用 Lucene 内部文档 ID 作为种子值,由于文档在合并后可能会被重新编号,因此随机值不可复现。为了使生成的随机值保持一致,可以提供 `seed` 和 `field` 参数。`field` 必须是启用了 `fielddata` 的字段(通常是数值字段)。评分使用 `seed`、`field` 的 `fielddata` 值,以及根据索引名称和分片(Shard)ID 计算出的盐值来计算。由于位于同一分片中的文档具有相同的索引名称和分片 ID,因此 `field` 值相同的文档会被分配相同的评分。要确保同一分片中的所有文档获得不同的评分,请使用一个对所有文档都具有唯一值的 `field`。一种选择是使用 `_seq_no` 字段。但如果选择该字段,当文档更新时,评分可能会因相应的 `_seq_no` 更新而发生变化。 + +以下查询使用带有 `seed` 和 `field` 的 `random_score` 函数: + +```json +GET blogs/_search +{ + "query": { + "function_score": { + "random_score": { + "seed": 20, + "field": "_seq_no" + } + } + } +} +``` + +## field value factor 函数 + +`field_value_factor` 函数使用指定文档字段的值重新计算评分。如果该字段是多值字段,则只使用其第一个值进行计算,其他值不予考虑。 + +`field_value_factor` 函数支持以下选项: + +- `field`:用于评分计算的字段。 + +- `factor`:一个可选系数,字段值会乘以该系数。默认值为 1。 + +- `modifier`:应用于字段值 $$v$$ 的修饰符之一。下表列出了所有支持的修饰符。 + + 修饰符 | 公式 | 描述 + :--- | :--- | :--- + `log`| $$\log v$$ | 取该值以 10 为底的对数。对非正数取对数是非法操作,会导致错误。对于介于 0(不含)和 1(含)之间的值,该函数返回的非负值会导致错误。建议使用 `log1p` 或 `log2p` 代替 `log`。 + `log1p`| $$\log (1 + v)$$ | 取 1 与该值之和以 10 为底的对数。 + `log2p`| $$\log (2 + v)$$ | 取 2 与该值之和以 10 为底的对数。 + `ln`| $$\ln v$$ | 取该值的自然对数。对非正数取对数是非法操作,会导致错误。对于介于 0(不含)和 1(含)之间的值,该函数返回的非负值会导致错误。建议使用 `ln1p` 或 `ln2p` 代替 `ln`。 + `ln1p`| $$\ln (1 + v)$$ | 取 1 与该值之和的自然对数。 + `ln2p`| $$\ln (2 + v)$$ | 取 2 与该值之和的自然对数。 + `reciprocal`| $$\frac {1}{v}$$ | 取该值的倒数。 + `square`| $$v^2$$ | 取该值的平方。 + `sqrt`| $$\sqrt v$$ | 取该值的平方根。对负数取平方根是非法操作,会导致错误。请确保 $$v$$ 为非负数。 + `none`| N/A | 不应用任何修饰符。 + +- `missing`:文档中缺少该字段时使用的值。`factor` 和 `modifier` 会应用于该值,而不是缺失的字段值。 + +例如,以下查询使用 `field_value_factor` 函数为 `views` 字段赋予更高的权重: + +```json +GET blogs/_search +{ + "query": { + "function_score": { + "field_value_factor": { + "field": "views", + "factor": 1.5, + "modifier": "log1p", + "missing": 1 + } + } + } +} +``` + +上述查询使用以下公式计算相关性评分: + +$$ \text{score} = \text{original score} \cdot \log(1 + 1.5 \cdot \text{views}) $$ + +## script score 函数 + +使用 `script_score` 函数,可以编写自定义脚本为文档评分,并可选择性地结合文档中字段的值。原始相关性评分可以通过 `_score` 变量访问。 + +::: warning 重要 +计算出的评分不能为负数,负评分会导致错误。文档评分是正的 32 位浮点值,精度更高的评分会被转换为最接近的 32 位浮点数。 +::: + +例如,以下查询使用 `script_score` 函数,根据原始评分以及博客文章的浏览数和点赞数来计算评分。为了降低浏览数和点赞数的权重,该公式取浏览数与点赞数之和的对数。为了在浏览数和点赞数为 `0` 时对数仍然有效,会在它们的和上加 `1`: + +```json +GET blogs/_search +{ + "query": { + "function_score": { + "query": {"match": {"name": "opensearch"}}, + "script_score": { + "script": "_score * Math.log(1 + doc['likes'].value + doc['views'].value)" + } + } + } +} +``` + +脚本会被编译和缓存以提升性能。因此,最好复用同一个脚本,并传入脚本所需的任何参数: + +```json +GET blogs/_search +{ + "query": { + "function_score": { + "query": { + "match": { "name": "opensearch" } + }, + "script_score": { + "script": { + "params": { + "add": 1 + }, + "source": "_score * Math.log(params.add + doc['likes'].value + doc['views'].value)" + } + } + } + } +} +``` + +## 衰减函数 + +在许多应用中,需要根据邻近程度或时间远近对结果进行排序,这可以通过衰减函数实现。衰减函数使用以下三种衰减曲线之一计算文档评分:高斯(Gaussian)、指数(exponential)或线性(linear)。 + +::: warning 重要 +衰减函数只能作用于[数值](/field-types/supported-field-types/numeric)、[日期](/field-types/supported-field-types/dates)和 [geopoint](/field-types/supported-field-types/geo-point) 字段。 +::: + +衰减函数根据 `origin`、`scale`、`offset` 和 `decay` 计算评分,如下图所示。 + +Decay function curves + +### 示例:geopoint 字段 + +假设你正在寻找一家离办公室较近的酒店。你创建了一个 `hotels` 索引(Index),并将 `location` 字段映射为 geopoint: + +```json +PUT hotels +{ + "mappings": { + "properties": { + "location": { + "type": "geo_point" + } + } + } +} +``` + +你索引了两个文档,分别对应附近的两家酒店: + +```json +PUT hotels/_doc/1 +{ + "name": "Hotel Within 200", + "location": { + "lat": 40.7105, + "lon": 74.00 + } +} +``` + +```json +PUT hotels/_doc/2 +{ + "name": "Hotel Outside 500", + "location": { + "lat": 40.7115, + "lon": 74.00 + } +} +``` + +`origin` 定义计算距离的起点(办公室位置)。`offset` 指定距起点的一段距离,在该距离之内的文档都会获得满分 1。你可以为距离办公室 200 英尺以内的酒店赋予相同的最高评分。`scale` 定义图形的衰减速率,`decay` 定义距起点 `scale` + `offset` 距离处的文档所获得的评分。超出 200 英尺半径后,你可能会决定:如果还要再走 300 英尺才能到达某家酒店(`scale` = 300 英尺),就为它分配原始评分的四分之一(`decay` = 0.25)。 + +你创建了以下查询,`origin` 位于 (74.00, 40.71): + +```json +GET hotels/_search +{ + "query": { + "function_score": { + "functions": [ + { + "exp": { + "location": { + "origin": "40.71,74.00", + "offset": "200ft", + "scale": "300ft", + "decay": 0.25 + } + } + } + ] + } + } +} +``` + +响应中包含这两家酒店。距离办公室 200 英尺以内的酒店评分为 1,而位于 500 英尺半径之外的酒店评分为 0.20,低于 `decay` 参数 0.25: + +
+ + 响应 + + +```json +{ + "took": 854, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "hotels", + "_id": "1", + "_score": 1, + "_source": { + "name": "Hotel Within 200", + "location": { + "lat": 40.7105, + "lon": 74 + } + } + }, + { + "_index": "hotels", + "_id": "2", + "_score": 0.20099315, + "_source": { + "name": "Hotel Outside 500", + "location": { + "lat": 40.7115, + "lon": 74 + } + } + } + ] + } +} +``` +
+ +### 参数 + +下表列出了 `gauss`、`exp` 和 `linear` 函数支持的所有参数。 + +参数 | 描述 +:--- | :--- +`origin` | 计算距离的起点。对于数值字段,必须以数字形式提供;对于日期字段,以日期形式提供;对于 geopoint 字段,以 geopoint 形式提供。对 geopoint 和数值字段为必需,对日期字段为可选(默认值为 `now`)。日期字段支持日期数学表达式(例如 `now-2d`)。 +`offset` | 定义距起点的一段距离,在该距离之内的文档评分为 1。可选。默认值为 0。 +`scale` | 距 `origin` 为 `scale` + `offset` 距离处的文档会被分配 `decay` 评分。必需。
对于数值字段,`scale` 可以是任意数字。
对于日期字段,`scale` 可以定义为带[单位](/api-reference/units)的数字(`5h`、`1d`)。如果未提供单位,`scale` 默认以毫秒为单位。
对于 geopoint 字段,`scale` 可以定义为带[单位](/api-reference/units)的数字(`1mi`、`5km`)。如果未提供单位,`scale` 默认以米为单位。 +`decay` | 定义距 `origin` 为 `scale` + `offset` 距离处的文档评分。可选。默认值为 0.5。 + +::: info 注意 +对于文档中缺失的字段,衰减函数返回的评分为 1。 +::: + +### 示例:数值字段 + +以下查询使用指数衰减函数,按评论数对博客文章进行优先级排序: + +```json +GET blogs/_search +{ + "query": { + "function_score": { + "functions": [ + { + "exp": { + "comments": { + "origin": "20", + "offset": "5", + "scale": "10" + } + } + } + ] + } + } +} +``` + +结果中的前两篇博客文章评分为 1,因为其中一篇位于起点(20),另一篇距离为 16,处于 offset 范围之内(文档获得满分的范围计算为 20 $$\pm$$ 5,即 [15, 25])。第三篇博客文章距 `origin` 为 `scale` + `offset` 距离(20 − (5 + 10) = 15),因此获得默认的 `decay` 评分(0.5): + +
+ + 响应 + + +```json +{ + "took": 3, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "blogs", + "_id": "1", + "_score": 1, + "_source": { + "name": "Semantic search in OpenSearch", + "views": 1200, + "likes": 150, + "comments": 16, + "date_posted": "2022-04-17" + } + }, + { + "_index": "blogs", + "_id": "2", + "_score": 1, + "_source": { + "name": "Get started with OpenSearch 2.7", + "views": 1400, + "likes": 100, + "comments": 20, + "date_posted": "2022-05-02" + } + }, + { + "_index": "blogs", + "_id": "3", + "_score": 0.5, + "_source": { + "name": "Distributed tracing with Data Prepper", + "views": 800, + "likes": 50, + "comments": 5, + "date_posted": "2022-04-25" + } + }, + { + "_index": "blogs", + "_id": "4", + "_score": 0.4352753, + "_source": { + "name": "A very old blog", + "views": 100, + "likes": 20, + "comments": 3, + "date_posted": "2000-04-25" + } + } + ] + } +} +``` +
+ +### 示例:日期字段 + +以下查询使用高斯衰减函数,优先返回在 04/24/2002 前后发布的博客文章: + +```json +GET blogs/_search +{ + "query": { + "function_score": { + "functions": [ + { + "gauss": { + "date_posted": { + "origin": "2022-04-24", + "offset": "1d", + "scale": "6d", + "decay": 0.25 + } + } + } + ] + } + } +} +``` + +在结果中,第一篇博客文章发布于 04/24/2022 前后一天以内,因此具有最高评分 1。第二篇博客文章发布于 04/17/2022,处于 `offset` + `scale`(`1d` + `6d`)范围内,因此评分等于 `decay`(0.25)。第三篇博客文章发布于 04/24/2022 之后 7 天以上,因此评分较低。最后一篇博客文章发布于多年前,因此评分为 0: + +
+ + 响应 + + +```json +{ + "took": 2, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "blogs", + "_id": "3", + "_score": 1, + "_source": { + "name": "Distributed tracing with Data Prepper", + "views": 800, + "likes": 50, + "comments": 5, + "date_posted": "2022-04-25" + } + }, + { + "_index": "blogs", + "_id": "1", + "_score": 0.25, + "_source": { + "name": "Semantic search in OpenSearch", + "views": 1200, + "likes": 150, + "comments": 16, + "date_posted": "2022-04-17" + } + }, + { + "_index": "blogs", + "_id": "2", + "_score": 0.15154076, + "_source": { + "name": "Get started with OpenSearch 2.7", + "views": 1400, + "likes": 100, + "comments": 20, + "date_posted": "2022-05-02" + } + }, + { + "_index": "blogs", + "_id": "4", + "_score": 0, + "_source": { + "name": "A very old blog", + "views": 100, + "likes": 20, + "comments": 3, + "date_posted": "2000-04-25" + } + } + ] + } +} +``` +
+ +### 多值字段 + +如果为衰减计算指定的字段包含多个值,可以使用 `multi_value_mode` 参数。该参数指定以下函数之一,用于确定参与计算的字段值: + +- `min`:(默认)距 `origin` 的最小距离。 +- `max`:距 `origin` 的最大距离。 +- `avg`:距 `origin` 的平均距离。 +- `sum`:距 `origin` 的所有距离之和。 + +例如,你索引了一个包含距离数组的文档: + +```json +PUT testindex/_doc/1 +{ + "distances": [1, 2, 3, 4, 5] +} +``` + +以下查询使用多值字段 `distances` 的 `max` 距离来计算衰减: + +```json +GET testindex/_search +{ + "query": { + "function_score": { + "functions": [ + { + "exp": { + "distances": { + "origin": "6", + "offset": "5", + "scale": "1" + }, + "multi_value_mode": "max" + } + } + ] + } + } +} +``` + +由于距起点的最大距离(1)处于距 `origin` 的 `offset` 范围之内,该文档获得评分 1: + +```json +{ + "took": 3, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "testindex", + "_id": "1", + "_score": 1, + "_source": { + "distances": [ + 1, + 2, + 3, + 4, + 5 + ] + } + } + ] + } +} +``` + +### 衰减曲线计算 + +以下公式定义了各种衰减函数的评分计算方式($$v$$ 表示文档字段值)。 + +**高斯(Gaussian)** + +$$ \text{score} = \exp \left(-\frac {(\max(0, \lvert v - \text{origin} \rvert - \text{offset}))^2} {2\sigma^2} \right), $$ + +其中 $$\sigma$$ 的计算方式确保在距 `origin` 为 `offset` + `scale` 距离处的评分等于 `decay`: + +$$ \sigma^2 = - \frac {\text{scale}^2} {2 \ln(\text{decay})} $$ + +**指数(Exponential)** + +$$ \text{score} = \exp (\lambda \cdot \max(0, \lvert v - \text{origin} \rvert - \text{offset})),$$ + +其中 $$\lambda$$ 的计算方式确保在距 `origin` 为 `offset` + `scale` 距离处的评分等于 `decay`: + +$$\lambda = \frac {\ln(\text{decay})} {\text{scale}} $$ + +**线性(Linear)** + +$$ \text{score} = \max \left(\frac {s - \max(0, \lvert v - \text{origin} \rvert - \text{offset})} {s} \right), $$ + +其中 $$s$$ 的计算方式确保在距 `origin` 为 `offset` + `scale` 距离处的评分等于 `decay`: + +$$s = \frac {\text{scale}} {1 - \text{decay}}$$ + +## 使用多个评分函数 + +可以在函数评分查询的 `functions` 数组中列出多个评分函数。 + +### 合并多个函数的评分 + +不同的函数可能使用不同的评分尺度。例如,`random_score` 函数提供介于 0 和 1 之间的评分,而 `field_value_factor` 的评分没有特定的尺度。此外,你可能希望对不同函数给出的评分赋予不同的权重。要调整不同函数的评分,可以为每个函数指定 `weight` 参数,每个函数给出的评分会乘以 `weight`,得到该函数的最终评分。`weight` 参数必须在 `functions` 数组中提供,以便与 [weight 函数](#the-weight-function)区分开来。 + +各函数给出的评分通过 `score_mode` 参数进行合并,该参数可取以下值之一: + +- `multiply`:(默认)将各评分相乘。 +- `sum`:将各评分相加。 +- `avg`:取各评分的平均值。如果指定了 `weight`,则为[加权平均值](https://en.wikipedia.org/wiki/Weighted_arithmetic_mean)。例如,如果权重为 $$1$$ 的第一个函数返回评分 $$10$$,权重为 $$4$$ 的第二个函数返回评分 $$20$$,则平均值计算为 $$\frac {10 \cdot 1 + 20 \cdot 4}{1 + 4} = 18$$。 +- `first`:取第一个具有匹配过滤器的函数的评分。 +- `max`:取最大评分。 +- `min`:取最小评分。 + +### 指定评分上限 + +可以在 `max_boost` 参数中为函数评分指定上限。默认上限为 `float` 值的最大量级:(2 − 2−23) · 2127。 + +### 将所有函数的评分与查询评分合并 + +可以在 `boost_mode` 参数中指定如何将所有函数计算出的评分与查询评分合并,该参数可取以下值之一: + +- `multiply`:(默认)将查询评分乘以函数评分。 +- `replace`:忽略查询评分,使用函数评分。 +- `sum`:将查询评分与函数评分相加。 +- `avg`:取查询评分与函数评分的平均值。 +- `max`:取查询评分与函数评分中的较大者。 +- `min`:取查询评分与函数评分中的较小者。 + +### 过滤未达到阈值的文档 {#filtering-documents-that-dont-meet-a-threshold} + +更改相关性评分不会改变匹配文档的列表。要排除一些未达到阈值的文档,请在 `min_score` 参数中指定阈值。查询返回的所有文档都会先计算评分,然后使用该阈值进行过滤。 + +### 示例 + +以下请求搜索包含 "OpenSearch Data Prepper" 这些单词的博客文章,优先返回在 04/24/2022 前后发布的文章,同时也会考虑浏览数和点赞数。最后,将截止阈值设置为评分 10: + +```json +GET blogs/_search +{ + "query": { + "function_score": { + "boost": "5", + "functions": [ + { + "gauss": { + "date_posted": { + "origin": "2022-04-24", + "offset": "1d", + "scale": "6d" + } + }, + "weight": 1 + }, + { + "gauss": { + "likes": { + "origin": 200, + "scale": 200 + } + }, + "weight": 4 + }, + { + "gauss": { + "views": { + "origin": 1000, + "scale": 800 + } + }, + "weight": 2 + } + ], + "query": { + "match": { + "name": "opensearch data prepper" + } + }, + "max_boost": 10, + "score_mode": "max", + "boost_mode": "multiply", + "min_score": 10 + } + } +} +``` + +结果中包含三篇匹配的博客文章: + +
+ + 响应 + + +```json +{ + "took": 14, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 3, + "relation": "eq" + }, + "max_score": 31.191923, + "hits": [ + { + "_index": "blogs", + "_id": "3", + "_score": 31.191923, + "_source": { + "name": "Distributed tracing with Data Prepper", + "views": 800, + "likes": 50, + "comments": 5, + "date_posted": "2022-04-25" + } + }, + { + "_index": "blogs", + "_id": "1", + "_score": 13.907352, + "_source": { + "name": "Semantic search in OpenSearch", + "views": 1200, + "likes": 150, + "comments": 16, + "date_posted": "2022-04-17" + } + }, + { + "_index": "blogs", + "_id": "2", + "_score": 11.150461, + "_source": { + "name": "Get started with OpenSearch 2.7", + "views": 1400, + "likes": 100, + "comments": 20, + "date_posted": "2022-05-02" + } + } + ] + } +} +``` +
diff --git a/i18n/zh/query-dsl/compound/hybrid.md b/i18n/zh/query-dsl/compound/hybrid.md new file mode 100644 index 00000000..acca122f --- /dev/null +++ b/i18n/zh/query-dsl/compound/hybrid.md @@ -0,0 +1,29 @@ +--- +title: 混合查询 +--- + +# 混合查询 + +可以使用混合(hybrid)查询将多个查询(Query)的相关性评分(Relevance Score)合并为给定文档(Document)的一个评分。混合查询包含一个由一个或多个查询组成的列表,并在分片(Shard)级别为每个子查询独立计算文档评分。子查询的重写在协调节点级别执行,以避免重复计算。 + +## 示例 + +使用 `hybrid` 查询之前,必须先设置机器学习(ML)模型、摄取文档,并配置一个带有 [`normalization-processor`](/search-plugins/search-pipelines/normalization-processor) 的搜索管道(Search Pipeline)。 + +要了解如何设置 ML 模型,请参阅[选择模型](/ml-commons-plugin/integrating-ml-models#choosing-a-model)。 + +设置好 ML 模型后,请按照[使用混合搜索](/search-plugins/hybrid-search#using-hybrid-search)中的步骤学习如何使用 `hybrid` 查询。 + +如需完整示例,请参阅[神经搜索教程](/search-plugins/neural-search-tutorial#tutorial)。 + +## 参数 + +下表列出了 `hybrid` 查询支持的所有顶级参数。 + +参数 | 描述 +:--- | :--- +`queries` | 由一个或多个用于匹配文档的查询子句组成的数组。文档必须至少匹配一个查询子句才能在结果中返回。所有查询子句产生的文档相关性评分会通过应用[搜索管道](/search-plugins/search-pipelines/)合并为一个评分。查询子句的最大数量为 5。必需。 + +## 禁用混合查询 + +混合查询默认处于启用状态。要在集群中禁用混合查询,请在 `opensearch.yml` 中将 `plugins.neural_search.hybrid_search_disabled` 设置为 `true`。 diff --git a/i18n/zh/query-dsl/compound/index.md b/i18n/zh/query-dsl/compound/index.md new file mode 100644 index 00000000..5c4b5f45 --- /dev/null +++ b/i18n/zh/query-dsl/compound/index.md @@ -0,0 +1,18 @@ +--- +title: 复合查询 +--- + +# 复合查询 + +复合查询(Compound Query)用作多个叶子子句或复合子句的包装器,用于合并它们的结果或修改它们的行为。 + +下表列出了所有复合查询类型。 + +查询类型 | 描述 +:--- | :--- +[`bool`](/query-dsl/compound/bool)(布尔)| 使用布尔逻辑组合多个查询子句。 +[`boosting`](/query-dsl/compound/boosting) | 在不将文档从搜索结果中移除的情况下更改文档的相关性评分(Relevance Score)。返回匹配 `positive` 查询的文档,但降低结果中匹配 `negative` 查询的文档的相关性。 +[`constant_score`](/query-dsl/compound/constant-score) | 包装一个查询或过滤器,并为所有匹配的文档分配一个常量评分。该评分等于 `boost` 值。 +[`dis_max`](/query-dsl/compound/disjunction-max)(析取最大值)| 返回匹配一个或多个查询子句的文档。如果文档匹配多个查询子句,则会被分配更高的相关性评分。相关性评分取所有匹配子句中的最高评分,并可选地加上其他匹配子句的评分与 tiebreaker 值的乘积。 +[`function_score`](/query-dsl/compound/function-score) | 使用你定义的函数重新计算查询所返回文档的相关性评分。 +[`hybrid`](/query-dsl/compound/hybrid) | 将多个查询的相关性评分合并为给定文档的一个评分。 diff --git a/i18n/zh/query-dsl/full-text/index.md b/i18n/zh/query-dsl/full-text/index.md new file mode 100644 index 00000000..737e7098 --- /dev/null +++ b/i18n/zh/query-dsl/full-text/index.md @@ -0,0 +1,26 @@ +--- +title: 全文查询 +--- + +# 全文查询 + +本页列出了所有全文查询(Full-text Query)类型和常用选项。可以使用许多可选字段来构建细致的搜索行为,因此建议先针对具有代表性的索引(Index)测试一些基本查询类型并验证输出,然后再执行带有多个选项的更高级或更复杂的搜索。 + +OpenSearch 使用 Apache Lucene 搜索库,它为数据的摄取、索引、搜索和聚合提供了高效的数据结构和算法。 + +要详细了解搜索查询类,请参阅 [Lucene query JavaDocs](https://lucene.apache.org/core/8_9_0/core/org/apache/lucene/search/Query.html)。 + +本节介绍的全文查询类型使用标准分析器(Analyzer),该分析器会在提交查询时自动分析文本。 + +下表列出了所有全文查询类型。 + +查询类型 | 描述 +:--- | :--- +[`intervals`](/query-dsl/full-text/intervals) | 允许对匹配词项的邻近程度和顺序进行细粒度控制。 +[`match`](/query-dsl/full-text/match) | 默认的全文查询,可用于模糊匹配以及短语搜索或邻近搜索。 +[`match_bool_prefix`](/query-dsl/full-text/match-bool-prefix) | 创建一个[布尔查询](/query-dsl/compound/bool),匹配位于任意位置的所有词项,并将最后一个词项视为前缀。 +[`match_phrase`](/query-dsl/full-text/match-phrase) | 与 `match` 查询类似,但匹配整个短语,允许的间隔由可配置的 slop 决定。 +[`match_phrase_prefix`](/query-dsl/full-text/match-phrase-prefix) | 与 `match_phrase` 查询类似,但将词项作为整个短语匹配,并将最后一个词项视为前缀。 +[`multi_match`](/query-dsl/full-text/multi-match) | 与 `match` 查询类似,但用于多个字段。 +[`query_string`](/query-dsl/full-text/query-string) | 使用严格的语法,在单个查询字符串中指定布尔条件和多字段搜索。 +[`simple_query_string`](/query-dsl/full-text/simple-query-string) | `query_string` 查询的一个更简单、不那么严格的版本。 diff --git a/i18n/zh/query-dsl/full-text/intervals.md b/i18n/zh/query-dsl/full-text/intervals.md new file mode 100644 index 00000000..760a811e --- /dev/null +++ b/i18n/zh/query-dsl/full-text/intervals.md @@ -0,0 +1,386 @@ +--- +title: Intervals +--- + +# Intervals 查询 + +intervals 查询(Query)根据匹配词项的邻近程度和顺序来匹配文档(Document)。它对指定字段中包含的词项应用一组*匹配规则*。该查询会生成跨越文本中词项的最小区间序列。可以组合这些区间,并按父级来源对其进行过滤。 + +假设有一个索引(Index),其中包含以下文档: + +```json +PUT testindex/_doc/1 +{ + "title": "key-value pairs are efficiently stored in a hash table" +} +``` + +```json +PUT /testindex/_doc/2 +{ + "title": "store key-value pairs in a hash map" +} +``` + +例如,以下查询搜索包含短语 `key-value pairs`(词项之间没有间隔)且其后跟随 `hash table` 或 `hash map` 的文档: + +```json +GET /testindex/_search +{ + "query": { + "intervals": { + "title": { + "all_of": { + "ordered": true, + "intervals": [ + { + "match": { + "query": "key-value pairs", + "max_gaps": 0, + "ordered": true + } + }, + { + "any_of": { + "intervals": [ + { + "match": { + "query": "hash table" + } + }, + { + "match": { + "query": "hash map" + } + } + ] + } + } + ] + } + } + } + } +} +``` + +该查询返回了两个文档: + +
+ + 响应 + + +```json +{ + "took": 1011, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.25, + "hits": [ + { + "_index": "testindex", + "_id": "2", + "_score": 0.25, + "_source": { + "title": "store key-value pairs in a hash map" + } + }, + { + "_index": "testindex", + "_id": "1", + "_score": 0.14285713, + "_source": { + "title": "key-value pairs are efficiently stored in a hash table" + } + } + ] + } +} +``` +
+ +## 参数 + +该查询接受字段名(``)作为顶级参数: + +```json +GET _search +{ + "query": { + "intervals": { + "": { + ... + } + } + } +} +``` + +`` 接受以下规则对象,这些规则对象用于根据词项、顺序和邻近程度来匹配文档。 + +规则 | 描述 +:--- | :--- +[`match`](#the-match-rule) | 匹配经过分析的文本。 +[`prefix`](#the-prefix-rule) | 匹配以指定字符集开头的词项。 +[`wildcard`](#the-wildcard-rule) | 使用通配符模式匹配词项。 +[`fuzzy`](#the-fuzzy-rule) | 匹配与所提供词项在指定编辑距离内相似的词项。 +[`all_of`](#the-all_of-rule) | 使用合取(`AND`)组合多个规则。 +[`any_of`](#the-any_of-rule) | 使用析取(`OR`)组合多个规则。 + +## `match` 规则 + +`match` 规则匹配经过分析的文本。下表列出了 `match` 规则支持的所有参数。 + +参数 | 必需/可选 | 数据类型 | 描述 +:--- | :--- | :--- | :--- +`query` | 必需 | String | 要搜索的文本。 +`analyzer` | 可选 | String | 用于分析 `query` 文本的[分析器](/analyzers/)(Analyzer)。默认值为 `` 指定的分析器。 +[`filter`](#the-filter-rule) | 可选 | Interval filter rule object | 用于过滤返回区间的规则。 +`max_gaps` | 可选 | Integer | 匹配词项之间允许的最大位置数。间隔超过 `max_gaps` 的词项不被视为匹配。如果未指定 `max_gaps` 或将其设置为 `-1`,则无论词项位置如何都视为匹配。如果 `max_gaps` 设置为 `0`,匹配的词项必须彼此相邻。默认值为 `-1`。 +`ordered` | 可选 | Boolean | 指定匹配的词项是否必须按指定顺序出现。默认值为 `false`。 +`use_field` | 可选 | String | 指定搜索该字段,而不是顶级 。词项使用为该字段指定的搜索分析器进行分析。通过指定 `use_field`,可以像搜索同一个字段一样跨多个字段进行搜索。例如,如果将同一文本同时索引到经过词干提取和未经词干提取的字段中,就可以搜索与未提取词干的词元(Token)相邻的已提取词干的词元。 + +## `prefix` 规则 + +`prefix` 规则匹配以指定字符集(前缀)开头的词项。前缀最多可扩展匹配 128 个词项。如果前缀匹配超过 128 个词项,则返回错误。下表列出了 `prefix` 规则支持的所有参数。 + +参数 | 必需/可选 | 数据类型 | 描述 +:--- | :--- | :--- | :--- +`prefix` | 必需 | String | 用于匹配词项的前缀。 +`analyzer` | 可选 | String | 用于规范化 `prefix` 的[分析器](/analyzers/)。默认值为 `` 指定的分析器。 +`use_field` | 可选 | String | 指定搜索该字段,而不是顶级 。除非指定了 `analyzer`,否则 `prefix` 会使用为该字段指定的搜索分析器进行规范化。 + +## `wildcard` 规则 + +`wildcard` 规则使用通配符模式匹配词项。通配符模式最多可扩展匹配 128 个词项。如果该模式匹配超过 128 个词项,则返回错误。下表列出了 `wildcard` 规则支持的所有参数。 + +参数 | 必需/可选 | 数据类型 | 描述 +:--- | :--- | :--- | :--- +`pattern` | 必需 | String | 用于匹配词项的通配符模式。指定 `?` 匹配任意单个字符,指定 `*` 匹配零个或多个字符。 +`analyzer` | 可选 | String | 用于规范化 `pattern` 的[分析器](/analyzers/)。默认值为 `` 指定的分析器。 +`use_field` | 可选 | String | 指定搜索该字段,而不是顶级 。除非指定了 `analyzer`,否则 `prefix` 会使用为该字段指定的搜索分析器进行规范化。 + +::: warning 重要 +指定以 `*` 或 `?` 开头的模式可能会降低搜索性能,因为这会增加匹配词项所需的迭代次数。 +::: + +## `fuzzy` 规则 + +`fuzzy` 规则匹配与所提供词项在指定编辑距离内相似的词项。模糊模式最多可扩展匹配 128 个词项。如果该模式匹配超过 128 个词项,则返回错误。下表列出了 `fuzzy` 规则支持的所有参数。 + +参数 | 必需/可选 | 数据类型 | 描述 +:--- | :--- | :--- | :--- +`term` | 必需 | String | 要匹配的词项。 +`analyzer` | 可选 | String | 用于规范化 `term` 的[分析器](/analyzers/)。默认值为 `` 指定的分析器。 +`fuzziness` | 可选 | String | 在判断词项是否与某个值匹配时,将一个单词变为另一个单词所需的字符编辑(插入、删除、替换)次数。例如,`wined` 与 `wind` 之间的距离为 1。有效值为非负整数或 `AUTO`。默认值 `AUTO` 会根据每个词项的长度选择一个值,适用于大多数使用场景。 +`transpositions` | 可选 | Boolean | 将 `transpositions` 设置为 `true`(默认值)时,会在 `fuzziness` 选项的插入、删除和替换操作之外,增加相邻字符交换操作。例如,如果 `transpositions` 为 true,`wind` 与 `wnid` 之间的距离为 1(交换 "n" 和 "i");如果为 false,则距离为 2(删除 "n",再插入 "n")。如果 `transpositions` 为 `false`,`rewind` 和 `wnid` 与 `wind` 的距离相同(均为 2),尽管从人的角度来看,`wnid` 明显只是一个拼写错误。默认值适用于大多数使用场景。 +`prefix_length`| 可选 | Integer | 模糊匹配时保持不变的开头字符数。默认值为 0。 +`use_field` | 可选 | String | 指定搜索该字段,而不是顶级 。除非指定了 `analyzer`,否则 `term` 会使用为该字段指定的搜索分析器进行规范化。 + +## `all_of` 规则 {#the-allof-rule} + +`all_of` 规则使用合取(`AND`)组合多个规则。下表列出了 `all_of` 规则支持的所有参数。 + +参数 | 必需/可选 | 数据类型 | 描述 +:--- | :--- | :--- | :--- +`intervals` | 必需 | Array of rule objects | 要组合的规则数组。文档必须匹配所有规则才能在结果中返回。 +[`filter`](#the-filter-rule) | 可选 | Interval filter rule object | 用于过滤返回区间的规则。 +`max_gaps` | 可选 | Integer | 匹配词项之间允许的最大位置数。间隔超过 `max_gaps` 的词项不被视为匹配。如果未指定 `max_gaps` 或将其设置为 `-1`,则无论词项位置如何都视为匹配。如果 `max_gaps` 设置为 `0`,匹配的词项必须彼此相邻。默认值为 `-1`。 +`ordered` | 可选 | Boolean | 如果为 `true`,规则生成的区间应按指定顺序出现。默认值为 `false`。 + +## `any_of` 规则 {#the-anyof-rule} + +`any_of` 规则使用析取(`OR`)组合多个规则。下表列出了 `any_of` 规则支持的所有参数。 + +参数 | 必需/可选 | 数据类型 | 描述 +:--- | :--- | :--- | :--- +`intervals` | 必需 | Array of rule objects | 要组合的规则数组。文档必须至少匹配一个规则才能在结果中返回。 +[`filter`](#the-filter-rule) | 可选 | Interval filter rule object | 用于过滤返回区间的规则。 + +## `filter` 规则 + +`filter` 规则用于限制结果。下表列出了 `filter` 规则支持的所有参数。 + +参数 | 必需/可选 | 数据类型 | 描述 +:--- | :--- | :--- | :--- +`after` | 可选 | Query object | 用于返回位于 filter 规则所指定区间之后的区间的查询。 +`before` | 可选 | Query object | 用于返回位于 filter 规则所指定区间之前的区间的查询。 +`contained_by` | 可选 | Query object | 用于返回被 filter 规则所指定区间包含的区间的查询。 +`containing` | 可选 | Query object | 用于返回包含 filter 规则所指定区间的区间的查询。 +`not_contained_by` | 可选 | Query object | 用于返回未被 filter 规则所指定区间包含的区间的查询。 +`not_containing` | 可选 | Query object | 用于返回不包含 filter 规则所指定区间的区间的查询。 +`not_overlapping` | 可选 | Query object | 用于返回与 filter 规则所指定区间不重叠的区间的查询。 +`overlapping` | 可选 | Query object | 用于返回与 filter 规则所指定区间重叠的区间的查询。 +`script` | 可选 | Script object | 用于匹配文档的脚本。该脚本必须返回 `true` 或 `false`。 + +#### 示例:过滤器 + +以下查询搜索包含单词 `pairs` 和 `hash`、两者相距不超过五个位置且中间不包含单词 `efficiently` 的文档: + +```json +POST /testindex/_search +{ + "query": { + "intervals" : { + "title" : { + "match" : { + "query" : "pairs hash", + "max_gaps" : 5, + "filter" : { + "not_containing" : { + "match" : { + "query" : "efficiently" + } + } + } + } + } + } + } +} +``` + +响应中只包含文档 2: + +
+ + 响应 + + +```json +{ + "took": 2, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.25, + "hits": [ + { + "_index": "testindex", + "_id": "2", + "_score": 0.25, + "_source": { + "title": "store key-value pairs in a hash map" + } + } + ] + } +} +``` +
+ +#### 示例:脚本过滤器 + +此外,也可以使用以下变量编写自己的脚本过滤器,并将其包含在 `intervals` 查询中: + +- `interval.start`:区间开始的位置(词项编号)。 +- `interval.end`:区间结束的位置(词项编号)。 +- `interval.gap`:词项之间的单词数。 + +例如,以下查询在指定区间内搜索彼此相邻的单词 `map` 和 `hash`。词项从 0 开始编号,因此在文本 `store key-value pairs in a hash map` 中,`store` 位于位置 0,`key` 位于位置 `1`,依此类推。指定的区间应在 `a` 之后开始,并在字符串末尾之前结束: + +```json +POST /testindex/_search +{ + "query": { + "intervals" : { + "title" : { + "match" : { + "query" : "map hash", + "filter" : { + "script" : { + "source" : "interval.start > 5 && interval.end < 8 && interval.gaps == 0" + } + } + } + } + } + } +} +``` + +响应中包含文档 2: + +
+ + 响应 + + +```json +{ + "took": 1, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.5, + "hits": [ + { + "_index": "testindex", + "_id": "2", + "_score": 0.5, + "_source": { + "title": "store key-value pairs in a hash map" + } + } + ] + } +} +``` +
+ +## 区间最小化 + +为了确保查询以线性时间运行,`intervals` 查询会对区间进行最小化。例如,假设某个文档包含文本 `a b c d c`。可以使用以下查询搜索被 `a` 和 `c` 包含的 `d`: + +```json +POST /testindex/_search +{ + "query": { + "intervals" : { + "my_text" : { + "match" : { + "query" : "d", + "filter" : { + "contained_by" : { + "match" : { + "query" : "a c" + } + } + } + } + } + } + } +} +``` + +该查询不会返回任何结果,因为它匹配了前两个词项 `a c`,而在这两个词项之间找不到 `d`。 diff --git a/i18n/zh/query-dsl/full-text/match-bool-prefix.md b/i18n/zh/query-dsl/full-text/match-bool-prefix.md new file mode 100644 index 00000000..77bfea2b --- /dev/null +++ b/i18n/zh/query-dsl/full-text/match-bool-prefix.md @@ -0,0 +1,217 @@ +--- +title: Match 布尔前缀 +--- + +# Match 布尔前缀查询 + +`match_bool_prefix` 查询(Query)会分析提供的搜索字符串,并根据字符串中的词项(Term)构建一个[布尔查询](/query-dsl/compound/bool)。除最后一个词项外,其余每个词项都作为完整单词进行匹配,最后一个词项则作为前缀使用。`match_bool_prefix` 查询返回包含这些完整词项或以前缀词项开头的词项的文档(Document),词项顺序不限。 + +以下示例展示了一个基本的 `match_bool_prefix` 查询: + +```json +GET _search +{ + "query": { + "match_bool_prefix": { + "title": "the wind" + } + } +} +``` + +如需传递其他参数,可以使用展开语法: + +```json +GET _search +{ + "query": { + "match_bool_prefix": { + "title": { + "query": "the wind", + "analyzer": "stop" + } + } + } +} +``` + +## 示例 + +例如,假设某个索引(Index)包含以下文档: + +```json +PUT testindex/_doc/1 +{ + "title": "The wind rises" +} +``` + +```json +PUT testindex/_doc/2 +{ + "title": "Gone with the wind" + +} +``` + +以下 `match_bool_prefix` 查询搜索完整单词 `rises` 以及以 `wi` 开头的单词,顺序不限: + +```json +GET testindex/_search +{ + "query": { + "match_bool_prefix": { + "title": "rises wi" + } + } +} +``` + +上述查询等价于以下布尔查询: + +```json +GET testindex/_search +{ + "query": { + "bool" : { + "should": [ + { "term": { "title": "rises" }}, + { "prefix": { "title": "wi"}} + ] + } + } +} +``` + +响应中包含这两个文档: + +
+ + 响应 + + +```json +{ + "took": 15, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1.73617, + "hits": [ + { + "_index": "testindex", + "_id": "1", + "_score": 1.73617, + "_source": { + "title": "The wind rises" + } + }, + { + "_index": "testindex", + "_id": "2", + "_score": 1, + "_source": { + "title": "Gone with the wind" + } + } + ] + } +} +``` + +
+ +## `match_bool_prefix` 查询与 `match_phrase_prefix` 查询 + +`match_bool_prefix` 查询匹配任意位置的词项,而 `match_phrase_prefix` 查询将词项作为一个完整短语进行匹配。为了说明二者的区别,再来看上一节中的 `match_bool_prefix` 查询: + +```json +GET testindex/_search +{ + "query": { + "match_bool_prefix": { + "title": "rises wi" + } + } +} +``` + +`The wind rises` 和 `Gone with the wind` 都与搜索词项匹配,因此查询返回这两个文档。 + +现在对同一个索引运行 `match_phrase_prefix` 查询: + +```json +GET testindex/_search +{ + "query": { + "match_phrase_prefix": { + "title": "rises wi" + } + } +} +``` + +响应中不返回任何文档,因为没有文档按指定顺序包含短语 `rises wi`。 + +## 分析器 + +默认情况下,对 `text` 字段运行查询时,搜索文本会使用与该字段关联的索引分析器(Analyzer)进行分析。你可以在 `analyzer` 参数中指定其他搜索分析器: + +```json +GET testindex/_search +{ + "query": { + "match_bool_prefix": { + "title": { + "query": "rise the wi", + "analyzer": "stop" + } + } + } +} +``` + +## 参数 + +该查询接受字段名称(``)作为顶级参数: + +```json +GET _search +{ + "query": { + "match_bool_prefix": { + "": { + "query": "text to search for", + ... + } + } + } +} +``` + +`` 接受以下参数。除 `query` 外,所有参数均为可选。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`query` | String | 用于搜索的文本、数字、布尔值或日期。必需。 +`analyzer` | String | 用于对查询字符串文本进行分词的[分析器](/analyzers/)。默认值为 `default_field` 指定的索引时分析器。如果没有为 `default_field` 指定分析器,则 `analyzer` 为该索引的默认分析器。 +`fuzziness` | `AUTO`, `0`, or a positive integer | 在判断某个词项是否与某个值匹配时,将一个单词变为另一个单词所需的字符编辑(插入、删除、替换)次数。例如,`wined` 与 `wind` 之间的距离为 1。默认值 `AUTO` 会根据每个词项的长度选择一个值,适用于大多数场景。 +`fuzzy_rewrite` | String | 决定 OpenSearch 如何重写查询。有效值为 `constant_score`、`scoring_boolean`、`constant_score_boolean`、`top_terms_N`、`top_terms_boost_N` 和 `top_terms_blended_freqs_N`。如果 `fuzziness` 参数不为 `0`,查询默认使用 `top_terms_blended_freqs_${max_expansions}` 作为 `fuzzy_rewrite` 方法。默认值为 `constant_score`。 +`fuzzy_transpositions` | Boolean | 将 `fuzzy_transpositions` 设置为 `true`(默认值)时,会在 `fuzziness` 选项的插入、删除和替换操作之外,增加相邻字符的交换操作。例如,如果 `fuzzy_transpositions` 为 true(交换“n”和“i”),`wind` 与 `wnid` 之间的距离为 1;如果为 false(删除“n”,再插入“n”),距离为 2。如果 `fuzzy_transpositions` 为 false,`rewind` 和 `wnid` 与 `wind` 的距离相同(均为 2),尽管从人的角度来看,`wnid` 显然只是一个拼写错误。默认值适用于大多数场景。 +`max_expansions` | Positive integer | 查询最多可以扩展到的词项数。模糊查询会“扩展到”在 `fuzziness` 指定距离内的若干个匹配词项,然后 OpenSearch 尝试匹配这些词项。默认值为 `50`。 +`minimum_should_match` | Positive or negative integer, positive or negative percentage, combination | 如果查询字符串包含多个搜索词项并且使用 `or` 运算符,该参数指定文档被视为匹配时需要匹配的词项数。例如,如果 `minimum_should_match` 为 2,则 `wind often rising` 与 `The Wind Rises.` 不匹配;如果 `minimum_should_match` 为 `1`,则二者匹配。有关详细信息,请参阅 [Minimum should match](/query-dsl/minimum-should-match)。 +`operator` | String | 如果查询字符串包含多个搜索词项,该参数指定文档被视为匹配时是需要所有词项都匹配(`and`),还是只需一个词项匹配(`or`)。有效值为 `or` 和 `and`。默认值为 `or`。 +`prefix_length` | Non-negative integer | 不参与模糊匹配的前导字符数。默认值为 `0`。 + +::: info 注意 +`fuzziness`、`fuzzy_transpositions`、`fuzzy_rewrite`、`max_expansions` 和 `prefix_length` 参数可以应用于除最后一个词项以外的所有词项所构建的词项子查询,对为最后一个词项构建的前缀查询不起作用。 +::: diff --git a/i18n/zh/query-dsl/full-text/match-phrase-prefix.md b/i18n/zh/query-dsl/full-text/match-phrase-prefix.md new file mode 100644 index 00000000..07d05baf --- /dev/null +++ b/i18n/zh/query-dsl/full-text/match-phrase-prefix.md @@ -0,0 +1,137 @@ +--- +title: Match 短语前缀 +--- + +# Match 短语前缀查询 + +使用 `match_phrase_prefix` 查询(Query)可以指定一个按顺序匹配的短语,并返回包含该短语的文档(Document)。短语中最后一个不完整的词项(Term)会被解释为前缀,因此所有包含以该短语和最后一个词项的前缀开头的短语的文档都会被返回。 + +与 [match phrase](/query-dsl/full-text/match-phrase) 类似,但会根据查询字符串中的最后一个词项创建一个[前缀查询](https://lucene.apache.org/core/8_9_0/core/org/apache/lucene/search/PrefixQuery.html)。 + +有关 `match_phrase_prefix` 查询与 `match_bool_prefix` 查询之间的区别,请参阅 [`match_bool_prefix` 查询与 `match_phrase_prefix` 查询](/query-dsl/full-text/match-bool-prefix#the-match_bool_prefix-and-match_phrase_prefix-queries)。 + +以下示例展示了一个基本的 `match_phrase_prefix` 查询: + +```json +GET _search +{ + "query": { + "match_phrase_prefix": { + "title": "the wind" + } + } +} +``` + +如需传递其他参数,可以使用展开语法: + +```json +GET _search +{ + "query": { + "match_phrase_prefix": { + "title": { + "query": "the wind", + "analyzer": "stop" + } + } + } +} +``` + +## 示例 + +例如,假设某个索引(Index)包含以下文档: + +```json +PUT testindex/_doc/1 +{ + "title": "The wind rises" +} +``` + +```json +PUT testindex/_doc/2 +{ + "title": "Gone with the wind" + +} +``` + +以下 `match_phrase_prefix` 查询搜索完整单词 `wind`,且其后紧跟一个以 `ri` 开头的单词: + +```json +GET testindex/_search +{ + "query": { + "match_phrase_prefix": { + "title": "wind ri" + } + } +} +``` + +响应中包含匹配的文档: + +
+ + 响应 + + +```json +{ + "took": 6, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.92980814, + "hits": [ + { + "_index": "testindex", + "_id": "1", + "_score": 0.92980814, + "_source": { + "title": "The wind rises" + } + } + ] + } +} +``` +
+ +## 参数 + +该查询接受字段名称(``)作为顶级参数: + +```json +GET _search +{ + "query": { + "match_phrase": { + "": { + "query": "text to search for", + ... + } + } + } +} +``` + +`` 接受以下参数。除 `query` 外,所有参数均为可选。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`query` | String | 用于搜索的查询字符串。必需。 +`analyzer` | String | 用于对查询进行分词的[分析器](/analyzers/)(Analyzer)。 +`max_expansions` | Positive integer | 查询最多可以扩展到的词项数。模糊查询会“扩展到”在 `fuzziness` 指定距离内的若干个匹配词项,然后 OpenSearch 尝试匹配这些词项。默认值为 `50`。 +`slop` | `0` (default) or a positive integer | 控制查询中的单词在顺序错乱到何种程度时仍可视为匹配。引自 [Lucene 文档](https://lucene.apache.org/core/8_9_0/core/org/apache/lucene/search/PhraseQuery.html#getSlop--):“查询短语中各单词之间允许出现的其他单词数。例如,调换两个单词的顺序需要移动两次(第一次移动使两个单词重叠),因此若要允许短语重新排序,slop 至少为 2。值为 0 时要求精确匹配。” diff --git a/i18n/zh/query-dsl/full-text/match-phrase.md b/i18n/zh/query-dsl/full-text/match-phrase.md new file mode 100644 index 00000000..001a77eb --- /dev/null +++ b/i18n/zh/query-dsl/full-text/match-phrase.md @@ -0,0 +1,259 @@ +--- +title: Match 短语 +--- + +# Match 短语查询 + +使用 `match_phrase` 查询(Query)可以匹配按指定顺序包含某个精确短语的文档(Document)。通过提供 `slop` 参数,可以让短语匹配更加灵活。 + +`match_phrase` 查询会创建一个匹配词项(Term)序列的[短语查询](https://lucene.apache.org/core/8_9_0/core/org/apache/lucene/search/PhraseQuery.html)。 + +以下示例展示了一个基本的 `match_phrase` 查询: + +```json +GET _search +{ + "query": { + "match_phrase": { + "title": "the wind" + } + } +} +``` + +如需传递其他参数,可以使用展开语法: + +```json +GET _search +{ + "query": { + "match_phrase": { + "title": { + "query": "the wind", + "analyzer": "stop" + } + } + } +} +``` + +## 示例 + +例如,假设某个索引(Index)包含以下文档: + +```json +PUT testindex/_doc/1 +{ + "title": "The wind rises" +} +``` + +```json +PUT testindex/_doc/2 +{ + "title": "Gone with the wind" + +} +``` + +以下 `match_phrase` 查询搜索短语 `wind rises`,即单词 `wind` 后紧跟单词 `rises`: + +```json +GET testindex/_search +{ + "query": { + "match_phrase": { + "title": "wind rises" + } + } +} +``` + +响应中包含匹配的文档: + +
+ + 响应 + + +```json +{ + "took": 30, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.92980814, + "hits": [ + { + "_index": "testindex", + "_id": "1", + "_score": 0.92980814, + "_source": { + "title": "The wind rises" + } + } + ] + } +} +``` +
+ +## 分析器 + +默认情况下,对 `text` 字段运行查询时,搜索文本会使用与该字段关联的索引分析器(Analyzer)进行分析。你可以在 `analyzer` 参数中指定其他搜索分析器。例如,以下查询使用 `english` 分析器: + +```json +GET testindex/_search +{ + "query": { + "match_phrase": { + "title": { + "query": "the winds", + "analyzer": "english" + } + } + } +} +``` + +`english` 分析器会移除停用词 `the` 并执行词干提取,生成词元(Token)`wind`。两个文档都与该词元匹配,因此都会在结果中返回: + +
+ + 响应 + + +```json +{ + "took": 2, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.19363807, + "hits": [ + { + "_index": "testindex", + "_id": "1", + "_score": 0.19363807, + "_source": { + "title": "The wind rises" + } + }, + { + "_index": "testindex", + "_id": "2", + "_score": 0.17225474, + "_source": { + "title": "Gone with the wind" + } + } + ] + } +} +``` +
+ +## Slop + +如果提供了 `slop` 参数,查询会容许搜索词项的顺序发生变化。slop 指定查询短语中各单词之间允许出现的其他单词数。例如,在以下查询中,搜索文本的单词顺序与文档文本不同: + +```json +GET _search +{ + "query": { + "match_phrase": { + "title": { + "query": "wind rises the", + "slop": 3 + } + } + } +} +``` + +查询仍然会返回匹配的文档: + +
+ + 响应 + + +```json +{ + "took": 2, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.44026947, + "hits": [ + { + "_index": "testindex", + "_id": "1", + "_score": 0.44026947, + "_source": { + "title": "The wind rises" + } + } + ] + } +} +``` +
+ +## 空查询 + +有关可能出现的空查询,请参阅 [match 查询中的相应章节](/query-dsl/full-text/match#empty-query)。 + +## 参数 + +该查询接受字段名称(``)作为顶级参数: + +```json +GET _search +{ + "query": { + "match_phrase": { + "": { + "query": "text to search for", + ... + } + } + } +} +``` + +`` 接受以下参数。除 `query` 外,所有参数均为可选。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`query` | String | 用于搜索的查询字符串。必需。 +`analyzer` | String | 用于对查询字符串文本进行分词的[分析器](/analyzers/)。默认值为 `default_field` 指定的索引时分析器。如果没有为 `default_field` 指定分析器,则 `analyzer` 为该索引的默认分析器。 +`slop` | `0` (default) or a positive integer | 控制查询中的单词在顺序错乱到何种程度时仍可视为匹配。引自 [Lucene 文档](https://lucene.apache.org/core/8_9_0/core/org/apache/lucene/search/PhraseQuery.html#getSlop--):“查询短语中各单词之间允许出现的其他单词数。例如,调换两个单词的顺序需要移动两次(第一次移动使两个单词重叠),因此若要允许短语重新排序,slop 至少为 2。值为 0 时要求精确匹配。” +`zero_terms_query` | String | 在某些情况下,分析器会移除查询字符串中的所有词项。例如,`stop` 分析器会移除字符串 `an but this` 中的所有词项。在这种情况下,`zero_terms_query` 指定是不匹配任何文档(`none`)还是匹配所有文档(`all`)。有效值为 `none` 和 `all`。默认值为 `none`。 diff --git a/i18n/zh/query-dsl/full-text/match.md b/i18n/zh/query-dsl/full-text/match.md new file mode 100644 index 00000000..744707f8 --- /dev/null +++ b/i18n/zh/query-dsl/full-text/match.md @@ -0,0 +1,443 @@ +--- +title: Match +--- + +# Match 查询 + +使用 `match` 查询(Query)可以对特定的文档(Document)字段执行全文搜索。如果对 [`text`](/field-types/supported-field-types/text) 字段运行 `match` 查询,`match` 查询会[分析](/analyzers/)提供的搜索字符串,并返回与该字符串中任一词项(Term)匹配的文档。如果对精确值字段运行 `match` 查询,则返回与该精确值匹配的文档。搜索精确值字段的首选方式是使用过滤器(Filter),因为与查询不同,过滤器会被缓存。 + +以下示例展示了一个在 `title` 中搜索单词 `wind` 的基本 `match` 查询: + +```json +GET _search +{ + "query": { + "match": { + "title": "wind" + } + } +} +``` + +如需传递其他参数,可以使用展开语法: + +```json +GET _search +{ + "query": { + "match": { + "title": { + "query": "wind", + "analyzer": "stop" + } + } + } +} +``` + +## 示例 + +在以下示例中,你将使用包含以下文档的索引(Index): + +```json +PUT testindex/_doc/1 +{ + "title": "Let the wind rise" +} +``` + +```json +PUT testindex/_doc/2 +{ + "title": "Gone with the wind" + +} +``` + +```json +PUT testindex/_doc/3 +{ + "title": "Rise is gone" +} +``` + +## 运算符 + +如果对 `text` 字段运行 `match` 查询,文本会使用 `analyzer` 参数中指定的分析器(Analyzer)进行分析,然后使用 `operator` 参数中指定的运算符将生成的词元(Token)组合成一个布尔查询。默认运算符为 `OR`,因此查询 `wind rise` 会变为 `wind OR rise`。在本示例中,该查询返回文档 1--3,因为每个文档都包含与查询匹配的词项。要指定 `and` 运算符,请使用以下查询: + +```json +GET testindex/_search +{ + "query": { + "match": { + "title": { + "query": "wind rise", + "operator": "and" + } + } + } +} +``` + +该查询被构造为 `wind AND rise`,并返回文档 1 作为匹配文档: + +
+ + 响应 + + +```json +{ + "took": 17, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.2667098, + "hits": [ + { + "_index": "testindex", + "_id": "1", + "_score": 1.2667098, + "_source": { + "title": "Let the wind rise" + } + } + ] + } +} +``` + +
+ +### 最少应匹配数 + +通过指定 [`minimum_should_match`](/query-dsl/minimum-should-match) 参数,可以控制文档在结果中返回所必须匹配的最少词项数: + +```json +GET testindex/_search +{ + "query": { + "match": { + "title": { + "query": "wind rise", + "operator": "or", + "minimum_should_match": 2 + } + } + } +} +``` + +现在文档必须同时匹配两个词项,因此只返回文档 1(这等价于 `and` 运算符): + +
+ + 响应 + + +```json +{ + "took": 23, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.2667098, + "hits": [ + { + "_index": "testindex", + "_id": "1", + "_score": 1.2667098, + "_source": { + "title": "Let the wind rise" + } + } + ] + } +} +``` +
+ +## 分析器 + +由于本示例中没有显式指定分析器,因此使用默认的 `standard` 分析器。默认分析器不执行词干提取,因此如果运行查询 `the wind rises`,将不会得到任何结果,因为词元 `rises` 与词元 `rise` 不匹配。要更改搜索分析器,请在 `analyzer` 字段中指定。例如,以下查询使用 `english` 分析器: + +```json +GET testindex/_search +{ + "query": { + "match": { + "title": { + "query": "the wind rises", + "operator": "and", + "analyzer": "english" + } + } + } +} +``` + +`english` 分析器会移除停用词 `the` 并执行词干提取,生成词元 `wind` 和 `rise`。后一个词元与文档 1 匹配,因此文档 1 会在结果中返回: + +
+ + 响应 + + +```json +{ + "took": 19, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.2667098, + "hits": [ + { + "_index": "testindex", + "_id": "1", + "_score": 1.2667098, + "_source": { + "title": "Let the wind rise" + } + } + ] + } +} +``` +
+ +## 空查询 + +在某些情况下,分析器可能会移除查询中的所有词元。例如,`english` 分析器会移除停用词,因此在查询 `and OR or` 中,所有词元都会被移除。要检查分析器的行为,可以使用 [Analyze API](/api-reference/analyze-apis#apply-a-built-in-analyzer): + +```json +GET testindex/_analyze +{ + "analyzer" : "english", + "text" : "and OR or" +} +``` + +正如预期,该查询不会生成任何词元: + +```json +{ + "tokens": [] +} +``` + +你可以在 `zero_terms_query` 参数中指定空查询的行为。将 `zero_terms_query` 设置为 `all` 会返回索引中的所有文档,设置为 `none` 则不返回任何文档: + +```json +GET testindex/_search +{ + "query": { + "match": { + "title": { + "query": "and OR or", + "analyzer" : "english", + "zero_terms_query": "all" + } + } + } +} +``` + +## 模糊匹配 + +为了应对拼写错误,可以为查询指定 `fuzziness`,取值为以下任意一种: + +- 一个整数,指定此编辑所允许的最大 [Levenshtein 距离](https://en.wikipedia.org/wiki/Levenshtein_distance)。 +- `AUTO`: + - 0–2 个字符的字符串必须精确匹配。 + - 3–5 个字符的字符串允许 1 次编辑。 + - 超过 5 个字符的字符串允许 2 次编辑。 + +在大多数情况下,将 `fuzziness` 设置为默认值 `AUTO` 效果最好: + +```json +GET testindex/_search +{ + "query": { + "match": { + "title": { + "query": "wnid", + "fuzziness": "AUTO" + } + } + } +} +``` + +词元 `wnid` 与 `wind` 匹配,查询返回文档 1 和 2: + +
+ + 响应 + + +```json +{ + "took": 31, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.47501624, + "hits": [ + { + "_index": "testindex", + "_id": "1", + "_score": 0.47501624, + "_source": { + "title": "Let the wind rise" + } + }, + { + "_index": "testindex", + "_id": "2", + "_score": 0.47501624, + "_source": { + "title": "Gone with the wind" + } + } + ] + } +} +``` +
+ +### 前缀长度 + +拼写错误很少出现在单词开头。因此,你可以指定匹配前缀的最小长度,满足该长度的文档才会在结果中返回。例如,可以修改上述查询,加入 `prefix_length`: + +```json +GET testindex/_search +{ + "query": { + "match": { + "title": { + "query": "wnid", + "fuzziness": "AUTO", + "prefix_length": 2 + } + } + } +} +``` + +上述查询不返回任何结果。如果将 `prefix_length` 改为 1,则会返回文档 1 和 2,因为词元 `wnid` 的第一个字母没有拼错。 + +### 换位 + +在上一个示例中,单词 `wnid` 包含一处换位(`in` 被改成了 `ni`)。默认情况下,模糊匹配允许换位,但你可以将 `fuzzy_transpositions` 设置为 `false` 来禁止换位: + +```json +GET testindex/_search +{ + "query": { + "match": { + "title": { + "query": "wnid", + "fuzziness": "AUTO", + "fuzzy_transpositions": false + } + } + } +} +``` + +现在查询不返回任何结果。 + +## 同义词 + +如果使用 `synonym_graph` 过滤器,并且 `auto_generate_synonyms_phrase_query` 设置为 `true`(默认值),OpenSearch 会将查询解析为词项,然后组合这些词项,为多词项同义词生成[短语查询](https://lucene.apache.org/core/8_9_0/core/org/apache/lucene/search/PhraseQuery.html)。例如,如果将 `ba,batting average` 指定为同义词并搜索 `ba`,OpenSearch 会搜索 `ba OR "batting average"`。 + +要使用合取(AND)方式匹配多词项同义词,请将 `auto_generate_synonyms_phrase_query` 设置为 `false`: + +```json +GET /testindex/_search +{ + "query": { + "match": { + "text": { + "query": "good ba", + "auto_generate_synonyms_phrase_query": false + } + } + } +} +``` + +生成的查询为 `ba OR (batting AND average)`。 + +## 参数 + +该查询接受字段名称(``)作为顶级参数: + +```json +GET _search +{ + "query": { + "match": { + "": { + "query": "text to search for", + ... + } + } + } +} +``` + +`` 接受以下参数。除 `query` 外,所有参数均为可选。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`query` | String | 用于搜索的查询字符串。必需。 +`auto_generate_synonyms_phrase_query` | Boolean | 指定是否为多词项同义词自动创建 [match phrase 查询](/query-dsl/full-text/match-phrase)。例如,如果将 `ba,batting average` 指定为同义词并搜索 `ba`,OpenSearch 会搜索 `ba OR "batting average"`(如果此选项为 `true`)或 `ba OR (batting AND average)`(如果此选项为 `false`)。默认值为 `true`。 +`analyzer` | String | 用于对查询字符串文本进行分词的[分析器](/analyzers/)。默认值为 `default_field` 指定的索引时分析器。如果没有为 `default_field` 指定分析器,则 `analyzer` 为该索引的默认分析器。 +`boost` | Floating-point | 按给定的倍数提升该子句的权重。适用于在复合查询中为各子句设置权重。[0, 1) 范围内的值会降低相关性,大于 1 的值会提高相关性。默认值为 `1`。 +`enable_position_increments` | Boolean | 为 `true` 时,生成的查询会感知位置增量。当移除停用词在词项之间留下不需要的“间隙”时,此设置很有用。默认值为 `true`。 +`fuzziness` | String | 在判断某个词项是否与某个值匹配时,将一个单词变为另一个单词所需的字符编辑(插入、删除、替换)次数。例如,`wined` 与 `wind` 之间的距离为 1。有效值为非负整数或 `AUTO`。默认值 `AUTO` 会根据每个词项的长度选择一个值,适用于大多数场景。 +`fuzzy_rewrite` | String | 决定 OpenSearch 如何重写查询。有效值为 `constant_score`、`scoring_boolean`、`constant_score_boolean`、`top_terms_N`、`top_terms_boost_N` 和 `top_terms_blended_freqs_N`。如果 `fuzziness` 参数不为 `0`,查询默认使用 `top_terms_blended_freqs_${max_expansions}` 作为 `fuzzy_rewrite` 方法。默认值为 `constant_score`。 +`fuzzy_transpositions` | Boolean | 将 `fuzzy_transpositions` 设置为 `true`(默认值)时,会在 `fuzziness` 选项的插入、删除和替换操作之外,增加相邻字符的交换操作。例如,如果 `fuzzy_transpositions` 为 true(交换“n”和“i”),`wind` 与 `wnid` 之间的距离为 1;如果为 false(删除“n”,再插入“n”),距离为 2。如果 `fuzzy_transpositions` 为 false,`rewind` 和 `wnid` 与 `wind` 的距离相同(均为 2),尽管从人的角度来看,`wnid` 显然只是一个拼写错误。默认值适用于大多数场景。 +`lenient` | Boolean | 将 `lenient` 设置为 `true` 会忽略查询与文档字段之间的数据类型不匹配。例如,查询字符串 `"8.2"` 可以匹配 `float` 类型的字段。默认值为 `false`。 +`max_expansions` | Positive integer | 查询最多可以扩展到的词项数。模糊查询会“扩展到”在 `fuzziness` 指定距离内的若干个匹配词项,然后 OpenSearch 尝试匹配这些词项。默认值为 `50`。 +`minimum_should_match` | Positive or negative integer, positive or negative percentage, combination | 如果查询字符串包含多个搜索词项并且使用 `or` 运算符,该参数指定文档被视为匹配时需要匹配的词项数。例如,如果 `minimum_should_match` 为 2,则 `wind often rising` 与 `The Wind Rises.` 不匹配;如果 `minimum_should_match` 为 `1`,则二者匹配。有关详细信息,请参阅 [Minimum should match](/query-dsl/minimum-should-match)。 +`operator` | String | 如果查询字符串包含多个搜索词项,该参数指定文档被视为匹配时是需要所有词项都匹配(`AND`),还是只需一个词项匹配(`OR`)。有效值为:
- `OR`:字符串 `to be` 被解释为 `to OR be`
- `AND`:字符串 `to be` 被解释为 `to AND be`
默认值为 `OR`。 +`prefix_length` | Non-negative integer | 不参与模糊匹配的前导字符数。默认值为 `0`。 +`zero_terms_query` | String | 在某些情况下,分析器会移除查询字符串中的所有词项。例如,`stop` 分析器会移除字符串 `an but this` 中的所有词项。在这种情况下,`zero_terms_query` 指定是不匹配任何文档(`none`)还是匹配所有文档(`all`)。有效值为 `none` 和 `all`。默认值为 `none`。 diff --git a/i18n/zh/query-dsl/full-text/multi-match.md b/i18n/zh/query-dsl/full-text/multi-match.md new file mode 100644 index 00000000..0da06d00 --- /dev/null +++ b/i18n/zh/query-dsl/full-text/multi-match.md @@ -0,0 +1,908 @@ +--- +title: Multi-match +--- + +# Multi-match 查询 + +multi-match 操作的功能与 [match](/query-dsl/full-text/match) 操作类似。你可以使用 `multi_match` 查询(Query)搜索多个字段。 + +`^` 用于对某些字段进行“权重提升”。权重提升(boost)是一种乘数,使某个字段中的匹配比其他字段中的匹配具有更高的权重。在以下示例中,title 字段中对“wind”的匹配对 `_score` 的影响是 plot 字段中匹配的四倍: + +```json +GET _search +{ + "query": { + "multi_match": { + "query": "wind", + "fields": ["title^4", "plot"] + } + } +} +``` + +结果是,*The Wind Rises* 和 *Gone with the Wind* 等电影排在搜索结果的前面,而像 *Twister* 这样大概在剧情简介中包含“wind”的电影则排在后面。 + +字段名称中可以使用通配符。例如,以下查询会搜索 `speaker` 字段以及所有以 `play_` 开头的字段,例如 `play_name` 或 `play_title`: + +```json +GET _search +{ + "query": { + "multi_match": { + "query": "hamlet", + "fields": ["speaker", "play_*"] + } + } +} +``` + +如果未提供 `fields` 参数,`multi_match` 查询会搜索 `index.query. Default_field` 设置中指定的字段,该设置的默认值为 `*`。默认行为是提取映射(Mapping)中所有适用于[词项级查询](/query-dsl/term/)(Term-level Query)的字段,过滤掉元数据字段,然后组合所有提取出的字段来构建查询。 + +::: info 注意 +查询中子句的最大数量由 `indices.query.bool.max_clause_count` 设置定义,默认值为 1,024。 +::: + +## Multi-match 查询类型 + +OpenSearch 支持以下 multi-match 查询类型,它们的区别在于查询在内部的执行方式: + +- [`best_fields`](#best-fields)(默认):返回与任一字段匹配的文档(Document)。使用最佳匹配字段的 `_score`。 +- [`most_fields`](#most-fields):返回与任一字段匹配的文档。使用各匹配字段的组合评分。 +- [`cross_fields`](#cross-fields):将所有字段视为一个字段。以相同的 `analyzer` 处理各字段,并在任意字段中匹配单词。 +- [`phrase`](#phrase):对每个字段运行 `match_phrase` 查询。使用最佳匹配字段的 `_score`。 +- [`phrase_prefix`](#phrase-prefix):对每个字段运行 `match_phrase_prefix` 查询。使用最佳匹配字段的 `_score`。 +- [`bool_prefix`](#boolean-prefix):对每个字段运行 `match_bool_prefix` 查询。使用各匹配字段的组合评分。 + +## Best fields + +如果你搜索的两个单词共同表示一个概念,那么你会希望这两个单词相邻出现的结果评分更高。 + +例如,假设某个索引(Index)包含以下科学文章: + +```json +PUT /articles/_doc/1 +{ + "title": "Aurora borealis", + "description": "Northern lights, or aurora borealis, explained" +} +``` + +```json +PUT /articles/_doc/2 +{ + "title": "Sun deprivation in the Northern countries", + "description": "Using fluorescent lights for therapy" +} +``` + +你可以搜索标题或描述中包含 `northern lights` 的文章: + +```json +GET articles/_search +{ + "query": { + "multi_match" : { + "query": "northern lights", + "type": "best_fields", + "fields": [ "title", "description" ], + "tie_breaker": 0.3 + } + } +} +``` + +上述查询会作为以下 [`dis_max`](/query-dsl/compound/disjunction-max) 查询执行,其中每个字段对应一个 `match` 查询: + +```json +GET /articles/_search +{ + "query": { + "dis_max": { + "queries": [ + { "match": { "title": "northern lights" }}, + { "match": { "description": "northern lights" }} + ], + "tie_breaker": 0.3 + } + } +} +``` + +结果中包含两个文档,但文档 1 的评分更高,因为两个单词都出现在其 `description` 字段中: + +```json +{ + "took": 30, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.84407747, + "hits": [ + { + "_index": "articles", + "_id": "1", + "_score": 0.84407747, + "_source": { + "title": "Aurora borealis", + "description": "Northern lights, or aurora borealis, explained" + } + }, + { + "_index": "articles", + "_id": "2", + "_score": 0.6322521, + "_source": { + "title": "Sun deprivation in the Northern countries", + "description": "Using fluorescent lights for therapy" + } + } + ] + } +} +``` + +`best_fields` 查询使用最佳匹配字段的评分。如果指定了 `tie_breaker`,则使用以下算法计算评分: + +取最佳匹配字段的评分,再为所有其他匹配字段加上(`tie_breaker` * `_score`)。 + +## Most fields + +如果多个字段包含相同的文本,但这些文本以不同方式进行分析,请使用 `most_fields` 查询。例如,原始字段可能包含使用 `standard` 分析器(Analyzer)分析的文本,而另一个字段可能包含使用 `english` 分析器分析的相同文本,后者会执行词干提取: + +```json +PUT /articles +{ + "mappings": { + "properties": { + "title": { + "type": "text", + "fields": { + "english": { + "type": "text", + "analyzer": "english" + } + } + } + } + } +} +``` + +假设 `articles` 索引中索引了以下两个文档: + +```json +PUT /articles/_doc/1 +{ + "title": "Buttered toasts" +} +``` + +```json +PUT /articles/_doc/2 +{ + "title": "Buttering a toast" +} +``` + +`standard` 分析器将标题 `Buttered toast` 分析为 [`buttered`, `toasts`],将标题 `Buttering a toast` 分析为 [`buttering`, `a`, `toast`]。而由于词干提取,`english` 分析器会为这两个标题生成相同的词元(Token)列表 [`butter`, `toast`]。 + +你可以使用 `most_fields` 查询来返回尽可能多的文档: + +```json +GET /articles/_search +{ + "query": { + "multi_match": { + "query": "buttered toast", + "fields": [ + "title", + "title.english" + ], + "type": "most_fields" + } + } +} +``` + +上述查询会作为以下布尔查询执行: + +```json +GET articles/_search +{ + "query": { + "bool": { + "should": [ + { "match": { "title": "buttered toasts" }}, + { "match": { "title.english": "buttered toasts" }} + ] + } + } +} +``` + +计算相关性评分(Relevance Score)时,会将文档在所有 `match` 子句中的评分相加,然后将结果除以 `match` 子句的数量。 + +加入 `title.english` 字段后,可以检索到与词干化后的词元相匹配的第二个文档: + +```json +{ + "took": 9, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1.4418206, + "hits": [ + { + "_index": "articles", + "_id": "1", + "_score": 1.4418206, + "_source": { + "title": "Buttered toasts" + } + }, + { + "_index": "articles", + "_id": "2", + "_score": 0.09304003, + "_source": { + "title": "Buttering a toast" + } + } + ] + } +} +``` + +由于第一个文档的 `title` 和 `title.english` 字段都匹配,因此它的相关性评分更高。 + +## 运算符与最少应匹配数 + +`best_fields` 和 `most_fields` 查询以字段为单位生成 match 查询(每个字段一个)。因此,`minimum_should_match` 和 `operator` 参数会应用于每个字段,而这通常并不是期望的行为。 + +例如,假设 `customers` 索引包含以下文档: + +```json +PUT customers/_doc/1 +{ + "first_name": "John", + "last_name": "Doe" +} +``` + +```json +PUT customers/_doc/2 +{ + "first_name": "Jane", + "last_name": "Doe" +} +``` + +如果要在 `customers` 索引中搜索 `John Doe`,你可能会构造如下查询: + +```json +GET customers/_validate/query?explain +{ + "query": { + "multi_match" : { + "query": "John Doe", + "type": "best_fields", + "fields": [ "first_name", "last_name" ], + "operator": "and" + } + } +} +``` + +该查询中 `and` 运算符的意图是查找同时匹配 `John` 和 `Doe` 的文档。然而,该查询不返回任何结果。你可以运行 Validate API 来了解查询的执行方式: + +```json +GET customers/_validate/query?explain +{ + "query": { + "multi_match" : { + "query": "John Doe", + "type": "best_fields", + "fields": [ "first_name", "last_name" ], + "operator": "and" + } + } +} +``` + +从响应中可以看到,该查询试图让 `John` 和 `Doe` 同时与 `first_name` 字段或 `last_name` 字段匹配: + +```json +{ + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "valid": true, + "explanations": [ + { + "index": "customers", + "valid": true, + "explanation": "((+first_name:john +first_name:doe) | (+last_name:john +last_name:doe))" + } + ] +} +``` + +由于两个字段都不同时包含这两个单词,因此不返回任何结果。 + +跨字段搜索的更好方案是使用 [`cross_fields`](#cross-fields) 查询。与以字段为中心的 `best_fields` 和 `most_fields` 查询不同,`cross_fields` 查询以词项(Term)为中心。 + +## Cross fields + +使用 `cross_fields` 查询可以跨多个字段搜索数据。例如,如果索引包含客户数据,客户的名字和姓氏位于不同的字段中。然而,在搜索 `John Doe` 时,你希望得到 `first_name` 字段中包含 `John` 且 `last_name` 字段中包含 `Doe` 的文档。 + +在这种情况下,`most_fields` 查询无法正常工作,原因如下: + +- [`operator` 和 `minimum_should_match`](#operator-and-minimum-should-match) 参数以字段为单位而不是以词项为单位应用。 +- `first_name` 和 `last_name` 字段中的词频可能导致意外的结果。例如,如果某人的名字恰好是 `Doe`,那么包含该名字的文档会被认为是更好的匹配,因为这个名字不会出现在其他任何文档中。 + +`cross_fields` 查询会将查询字符串分析为单个词项,然后在任意字段中搜索每个词项,就好像这些字段是同一个字段一样。 + +以下是针对 `John Doe` 的 `cross_fields` 查询: + +```json +GET /customers/_search +{ + "query": { + "multi_match" : { + "query": "John Doe", + "type": "cross_fields", + "fields": [ "first_name", "last_name" ], + "operator": "and" + } + } +} +``` + +响应中只包含同时出现 `John` 和 `Doe` 的那个文档: + +```json +{ + "took": 19, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.8754687, + "hits": [ + { + "_index": "customers", + "_id": "1", + "_score": 0.8754687, + "_source": { + "first_name": "John", + "last_name": "Doe" + } + } + ] + } +} +``` + +你可以使用 Validate API 操作来了解上述查询的执行方式: + +```json +GET /customers/_validate/query?explain +{ + "query": { + "multi_match" : { + "query": "John Doe", + "type": "cross_fields", + "fields": [ "first_name", "last_name" ], + "operator": "and" + } + } +} +``` + +从响应中可以看到,该查询在至少一个字段中搜索所有词项: + +```json +{ + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "valid": true, + "explanations": [ + { + "index": "customers", + "valid": true, + "explanation": "+blended(terms:[last_name:john, first_name:john]) +blended(terms:[last_name:doe, first_name:doe])" + } + ] +} +``` + +因此,通过混合所有字段的词频来校正差异,就解决了各字段词频不同的问题。 + +::: info 注意 +`cross_fields` 查询通常只适用于 `boost` 为 1 的短字符串字段。在其他情况下,由于权重提升、词频和长度归一化对评分的影响方式,评分无法产生有意义的词项统计混合结果。 +::: + +::: info 注意 +`cross_fields` 查询不支持 `fuzziness` 参数。 +::: + +### 分析 + +`cross_fields` 查询只有在具有相同分析器的字段上才能作为以词项为中心的查询工作。具有相同分析器的字段会被分为一组,这些组再通过布尔查询组合起来。 + +例如,假设某个索引的 `first_name` 和 `last_name` 字段使用默认的 `standard` + 分析器进行分析,而它们的 `.edge` 子字段使用 edge n-gram 分析器进行分析: + +
+ + 响应 + + +```json +PUT customers +{ + "settings": { + "analysis": { + "analyzer": { + "my_analyzer": { + "tokenizer": "my_tokenizer" + } + }, + "tokenizer": { + "my_tokenizer": { + "type": "edge_ngram", + "min_gram": 2, + "max_gram": 10 + } + } + } + }, + "mappings": { + "properties": { + "first_name": { + "type": "text", + "fields": { + "edge": { + "type": "text", + "analyzer": "my_analyzer" + } + } + }, + "last_name": { + "type": "text", + "fields": { + "edge": { + "type": "text", + "analyzer": "my_analyzer" + } + } + } + } + } +} +``` + +
+ +在 `customers` 索引中索引一个文档: + +```json +PUT /customers/_doc/1 +{ + "first": "John", + "last": "Doe" +} +``` + +你可以使用 `cross_fields` 查询跨这些字段搜索 `John Doe`: + +```json +GET /customers/_search +{ + "query": { + "multi_match" : { + "query": "John", + "type": "cross_fields", + "fields": [ + "first_name", "first_name.edge", + "last_name", "last_name.edge" + ] + } + } +} +``` + +要查看查询的执行方式,可以运行 Validate API: + +```json +GET /customers/_validate/query?explain +{ + "query": { + "multi_match" : { + "query": "John", + "type": "cross_fields", + "fields": [ + "first_name", "first_name.edge", + "last_name", "last_name.edge" + ] + } + } +} +``` + +响应显示,`last_name` 和 `first_name` 字段被分为一组并被视为单个字段。同样,`last_name.edge` 和 `first_name.edge` 字段也被分为一组并被视为单个字段: + +```json +{ + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "valid": true, + "explanations": [ + { + "index": "customers", + "valid": true, + "explanation": "(blended(terms:[last_name:john, first_name:john]) | (blended(terms:[last_name.edge:Jo, first_name.edge:Jo]) blended(terms:[last_name.edge:Joh, first_name.edge:Joh]) blended(terms:[last_name.edge:John, first_name.edge:John])))" + } + ] +} +``` + +对上述这样的多个字段组使用 `operator` 或 `minimum_should_match` 参数,可能会导致[上一节](#operator-and-minimum-should-match)中所述的问题。为避免该问题,可以将上述查询改写为通过布尔查询组合的两个 `cross_fields` 子查询,并将 `minimum_should_match` 应用于其中一个子查询: + +```json +GET /customers/_search +{ + "query": { + "bool": { + "should": [ + { + "multi_match": { + "query": "John Doe", + "type": "cross_fields", + "fields": [ + "first_name", + "last_name" + ], + "minimum_should_match": "1" + } + }, + { + "multi_match": { + "query": "John Doe", + "type": "cross_fields", + "fields": [ + "first_name.edge", + "last_name.edge" + ] + } + } + ] + } + } +} +``` + +要为所有字段创建一个组,请在查询中指定分析器: + +```json +GET customers/_search +{ + "query": { + "multi_match" : { + "query": "John Doe", + "type": "cross_fields", + "analyzer": "standard", + "fields": [ "first_name", "last_name", "*.edge" ] + } + } +} +``` + +对上述查询运行 Validate API,可以看到查询的执行方式: + +```json +{ + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "valid": true, + "explanations": [ + { + "index": "customers", + "valid": true, + "explanation": "blended(terms:[last_name.edge:john, last_name:john, first_name:john, first_name.edge:john]) blended(terms:[last_name.edge:doe, last_name:doe, first_name:doe, first_name.edge:doe])" + } + ] +} +``` + +## Phrase + +`phrase` 查询的行为与 [`best_fields`](#best-fields) 查询类似,但使用 `match_phrase` 查询而不是 `match` 查询。 + +以下是针对 [`best_fields`](#best-fields) 一节中所述索引的 `phrase` 查询示例: + +```json +GET articles/_search +{ + "query": { + "multi_match" : { + "query": "northern lights", + "type": "phrase", + "fields": [ "title", "description" ] + } + } +} +``` + +上述查询会作为以下 [`dis_max`](/query-dsl/compound/disjunction-max) 查询执行,其中每个字段对应一个 `match_phrase` 查询: + +```json +GET articles/_search +{ + "query": { + "dis_max": { + "queries": [ + { "match_phrase": { "title": "northern lights" }}, + { "match_phrase": { "description": "northern lights" }} + ] + } + } +} +``` + +由于默认情况下 `phrase` 查询只在词项按相同顺序出现时才匹配文本,因此结果中只返回文档 1: + +
+ + 响应 + + +```json +{ + "took": 3, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.84407747, + "hits": [ + { + "_index": "articles", + "_id": "1", + "_score": 0.84407747, + "_source": { + "title": "Aurora borealis", + "description": "Northern lights, or aurora borealis, explained" + } + } + ] + } +} +``` +
+ +你可以使用 `slop` 参数,允许查询短语的单词之间出现其他单词。例如,以下查询在 `flourescent` 和 `therapy` 之间最多有两个单词时,仍将文本视为匹配: + +```json +GET articles/_search +{ + "query": { + "multi_match" : { + "query": "fluorescent therapy", + "type": "phrase", + "fields": [ "title", "description" ], + "slop": 2 + } + } +} +``` + +响应中包含文档 2: + +
+ + 响应 + + +```json +{ + "took": 3, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.7003825, + "hits": [ + { + "_index": "articles", + "_id": "2", + "_score": 0.7003825, + "_source": { + "title": "Sun deprivation in the Northern countries", + "description": "Using fluorescent lights for therapy" + } + } + ] + } +} +``` +
+ +当 `slop` 值小于 2 时,不返回任何文档。 + +::: info 注意 +`phrase` 查询不支持 `fuzziness` 参数。 +::: + +## Phrase prefix + +`phrase_prefix` 查询的行为与 [`phrase`](#phrase) 查询类似,但使用 `match_phrase_prefix` 查询而不是 `match_phrase` 查询。 + +以下是针对 [`best_fields`](#best-fields) 一节中所述索引的 `phrase_prefix` 查询示例: + +```json +GET articles/_search +{ + "query": { + "multi_match" : { + "query": "northern light", + "type": "phrase_prefix", + "fields": [ "title", "description" ] + } + } +} +``` + +上述查询会作为以下 [`dis_max`](/query-dsl/compound/disjunction-max) 查询执行,其中每个字段对应一个 `match_phrase_prefix` 查询: + +```json +GET articles/_search +{ + "query": { + "dis_max": { + "queries": [ + { "match_phrase_prefix": { "title": "northern light" }}, + { "match_phrase_prefix": { "description": "northern light" }} + ] + } + } +} +``` + +你可以使用 `slop` 参数,允许查询短语的单词之间出现其他单词。 + +::: info 注意 +`phrase_prefix` 查询不支持 `fuzziness` 参数。 +::: + +## Boolean prefix + +`bool_prefix` 查询为文档评分的方式与 [`most_fields`](#most-fields) 查询类似,但使用 [`match_bool_prefix`](/query-dsl/full-text/match-bool-prefix) 查询而不是 `match` 查询。 + +以下是针对 [`best_fields`](#best-fields) 一节中所述索引的 `bool_prefix` 查询示例: + +```json +GET articles/_search +{ + "query": { + "multi_match" : { + "query": "li northern", + "type": "bool_prefix", + "fields": [ "title", "description" ] + } + } +} +``` + +上述查询会作为以下 [`dis_max`](/query-dsl/compound/disjunction-max) 查询执行,其中每个字段对应一个 `match_bool_prefix` 查询: + +```json +GET articles/_search +{ + "query": { + "dis_max": { + "queries": [ + { "match_bool_prefix": { "title": "li northern" }}, + { "match_bool_prefix": { "description": "li northern" }} + ] + } + } +} +``` + +::: info 注意 +`fuzziness`、`prefix_length`、`max_expansions`、`fuzzy_rewrite` 和 `fuzzy_transpositions` 参数支持用于构建词项查询的那些词项,但对根据最后一个词项构建的前缀查询不起作用。 +::: + +## 参数 + +该查询接受以下参数。除 `query` 外,所有参数均为可选。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`query` | String | 用于搜索的查询字符串。必需。 +`auto_generate_synonyms_phrase_query` | Boolean | 指定是否为多词项同义词自动创建 [match phrase 查询](/query-dsl/full-text/match-phrase)。例如,如果将 `ba,batting average` 指定为同义词并搜索 `ba`,OpenSearch 会搜索 `ba OR "batting average"`(如果此选项为 `true`)或 `ba OR (batting AND average)`(如果此选项为 `false`)。默认值为 `true`。 +`analyzer` | String | 用于对查询字符串文本进行分词的[分析器](/analyzers/)。默认值为 `default_field` 指定的索引时分析器。如果没有为 `default_field` 指定分析器,则 `analyzer` 为该索引的默认分析器。 +`boost` | Floating-point | 按给定的倍数提升该子句的权重。适用于在复合查询中为各子句设置权重。[0, 1) 范围内的值会降低相关性,大于 1 的值会提高相关性。默认值为 `1`。 +`fields` | Array of strings | 要搜索的字段列表。如果未提供 `fields` 参数,`multi_match` 查询会搜索 `index.query. Default_field` 设置中指定的字段,该设置的默认值为 `*`。 +`fuzziness` | String | 在判断某个词项是否与某个值匹配时,将一个单词变为另一个单词所需的字符编辑(插入、删除、替换)次数。例如,`wined` 与 `wind` 之间的距离为 1。有效值为非负整数或 `AUTO`。默认值 `AUTO` 会根据每个词项的长度选择一个值,适用于大多数场景。不支持 `phrase`、`phrase_prefix` 和 `cross_fields` 查询。 +`fuzzy_rewrite` | String | 决定 OpenSearch 如何重写查询。有效值为 `constant_score`、`scoring_boolean`、`constant_score_boolean`、`top_terms_N`、`top_terms_boost_N` 和 `top_terms_blended_freqs_N`。如果 `fuzziness` 参数不为 `0`,查询默认使用 `top_terms_blended_freqs_${max_expansions}` 作为 `fuzzy_rewrite` 方法。默认值为 `constant_score`。 +`fuzzy_transpositions` | Boolean | 将 `fuzzy_transpositions` 设置为 `true`(默认值)时,会在 `fuzziness` 选项的插入、删除和替换操作之外,增加相邻字符的交换操作。例如,如果 `fuzzy_transpositions` 为 true(交换“n”和“i”),`wind` 与 `wnid` 之间的距离为 1;如果为 false(删除“n”,再插入“n”),距离为 2。如果 `fuzzy_transpositions` 为 false,`rewind` 和 `wnid` 与 `wind` 的距离相同(均为 2),尽管从人的角度来看,`wnid` 显然只是一个拼写错误。默认值适用于大多数场景。 +`lenient` | Boolean | 将 `lenient` 设置为 `true` 会忽略查询与文档字段之间的数据类型不匹配。例如,查询字符串 `"8.2"` 可以匹配 `float` 类型的字段。默认值为 `false`。 +`max_expansions` | Positive integer | 查询最多可以扩展到的词项数。模糊查询会“扩展到”在 `fuzziness` 指定距离内的若干个匹配词项,然后 OpenSearch 尝试匹配这些词项。默认值为 `50`。 +`minimum_should_match` | Positive or negative integer, positive or negative percentage, combination | 如果查询字符串包含多个搜索词项并且使用 `or` 运算符,该参数指定文档被视为匹配时需要匹配的词项数。例如,如果 `minimum_should_match` 为 2,则 `wind often rising` 与 `The Wind Rises.` 不匹配;如果 `minimum_should_match` 为 `1`,则二者匹配。有关详细信息,请参阅 [Minimum should match](/query-dsl/minimum-should-match)。 +`operator` | String | 如果查询字符串包含多个搜索词项,该参数指定文档被视为匹配时是需要所有词项都匹配(`AND`),还是只需一个词项匹配(`OR`)。有效值为:
- `OR`:字符串 `to be` 被解释为 `to OR be`
- `AND`:字符串 `to be` 被解释为 `to AND be`
默认值为 `OR`。 +`prefix_length` | Non-negative integer | 不参与模糊匹配的前导字符数。默认值为 `0`。 +`slop` | `0` (default) or a positive integer | 控制查询中的单词在顺序错乱到何种程度时仍可视为匹配。引自 [Lucene 文档](https://lucene.apache.org/core/8_9_0/core/org/apache/lucene/search/PhraseQuery.html#getSlop--):“查询短语中各单词之间允许出现的其他单词数。例如,调换两个单词的顺序需要移动两次(第一次移动使两个单词重叠),因此若要允许短语重新排序,slop 至少为 2。值为 0 时要求精确匹配。”支持 `phrase` 和 `phrase_prefix` 查询类型。 +`tie_breaker` | Floating-point | 一个介于 0 和 1.0 之间的系数,用于为匹配多个查询子句的文档赋予更高的权重。有关更多信息,请参阅 [`tie_breaker` 参数](#the-tie_breaker-parameter)。 +`type` | String | multi-match 查询类型。有效值为 `best_fields`、`most_fields`、`cross_fields`、`phrase`、`phrase_prefix`、`bool_prefix`。默认值为 `best_fields`。 +`zero_terms_query` | String | 在某些情况下,分析器会移除查询字符串中的所有词项。例如,`stop` 分析器会移除字符串 `an but this` 中的所有词项。在这种情况下,`zero_terms_query` 指定是不匹配任何文档(`none`)还是匹配所有文档(`all`)。有效值为 `none` 和 `all`。默认值为 `none`。 + +::: info 注意 +`phrase`、`phrase_prefix` 和 `cross_fields` 查询不支持 `fuzziness` 参数。 +::: + +::: info 注意 +只有 `phrase` 和 `phrase_prefix` 查询支持 `slop` 参数。 +::: + +### `tie_breaker` 参数 {#the-tiebreaker-parameter} + +每个词项级混合查询都会将文档评分计算为组内任一字段返回的最佳评分。所有混合查询的评分相加得到最终评分。你可以使用 `tie_breaker` 参数更改评分的计算方式。`tie_breaker` 参数接受以下值: + +- 0.0(`best_fields`、`cross_fields`、`phrase` 和 `phrase_prefix` 查询的默认值):取组内任一字段返回的单个最佳评分。 +- 1.0(`most_fields` 和 `bool_prefix` 查询的默认值):将组内所有字段的评分相加。 +- (0, 1) 范围内的浮点值:取最佳匹配字段的单个最佳评分,再为所有其他匹配字段加上(`tie_breaker` * `_score`)。 diff --git a/i18n/zh/query-dsl/full-text/query-string.md b/i18n/zh/query-dsl/full-text/query-string.md new file mode 100644 index 00000000..a679ae4e --- /dev/null +++ b/i18n/zh/query-dsl/full-text/query-string.md @@ -0,0 +1,631 @@ +--- +title: Query string +--- + +# Query string 查询 + +`query_string` 查询(Query)会根据 [query string 语法](#query-string-syntax)解析查询字符串。它可以用来创建功能强大而又简洁的查询,这些查询可以包含通配符并搜索多个字段。 + +::: info 注意 +使用 `query_string` 查询进行搜索时不会返回嵌套文档(Document)。要搜索嵌套字段,请使用 [`nested` 查询](/field-types/supported-field-types/nested)。 +::: + +::: warning 重要 +Query string 查询的语法很严格,语法无效时会返回错误。因此,它不太适合搜索框类应用。如需语法不那么严格的替代方案,可以考虑使用 [`simple_query_string` 查询](/query-dsl/full-text/simple-query-string)。如果不需要支持查询语法,请使用 [`match` 查询](/query-dsl/full-text/match)。 +::: + +## Query string 语法 + +Query string 语法基于 [Apache Lucene 查询语法](https://lucene.apache.org/core/2_9_4/queryparsersyntax.html)。 + +你可以在以下场景中使用 query string 语法: + +1. 在 `query_string` 查询中,例如: + ```json + GET _search + { + "query": { + "query_string": { + "query": "the wind AND (rises OR rising)" + } + } + } + ``` + +1. 在 OpenSearch Dashboards 的 Discover 或 Dashboard 应用中关闭 DQL 后,如下图所示。 + ![在 OpenSearch Dashboards Discover 中使用 query string 语法](/images/discover-lucene-syntax.png) + + + ::: tip 提示 + DQL 和 Query string query(Lucene)语言是 Discover 和 Dashboards 中搜索栏的两种语言选项。要比较这两种语言选项,请参阅 [Discover 和 Dashboard 搜索栏](/dashboards/#discover-and-dashboard-search-bar)。 + ::: + +1. 使用 HTTP 请求查询参数进行搜索时,例如: + ```json + GET _search?q=wind + ``` + +查询字符串由*词项*和*运算符*组成。词项(Term)是单个单词(例如,在查询 `wind rises` 中,词项为 `wind` 和 `rises`)。如果多个词项用引号括起来,它们会被视为一个短语,其中的单词按出现顺序进行匹配(例如 `"wind rises"`)。运算符(例如 `OR`、`AND` 和 `NOT`)指定了用于解释查询字符串中文本的布尔逻辑。 + +本节中的示例使用一个包含以下映射(Mapping)和文档的索引(Index): + +```json +PUT /testindex +{ + "mappings": { + "properties": { + "title": { + "type": "text", + "fields": { + "english": { + "type": "text", + "analyzer": "english" + } + } + } + } + } +} +``` + +```json +PUT /testindex/_doc/1 +{ + "title": "The wind rises" +} +``` + +```json +PUT /testindex/_doc/2 +{ + "title": "Gone with the wind", + "description": "A 1939 American epic historical film" +} +``` + +```json +PUT /testindex/_doc/3 +{ + "title": "Windy city" +} +``` + +```json +PUT /testindex/_doc/4 +{ + "article title": "Wind turbines" +} +``` + +## 保留字符 + +以下是 query string 查询的保留字符列表: + +`+`, `-`, `=`, `&&`, `||`, `>`, `<`, `!`, `(`, `)`,`{`, `}`, `[`, `]`, `^`, `"`, `~`, `*`, `?`, `:`, `\`, `/` + +::: tip 提示 +使用反斜杠(`\`)转义保留字符。发送 JSON 请求时,请使用双反斜杠(`\\`)转义保留字符(由于反斜杠字符本身也是保留字符,因此必须再用一个反斜杠对其进行转义)。 +::: + +例如,要搜索表达式 `2*3`,请将查询字符串指定为 `2\\*3`: + +```json +GET /testindex/_search +{ + "query": { + "query_string": { + "query": "title: 2\\*3" + } + } +} +``` + +::: warning 重要 +`>` 和 `<` 符号不能转义,它们会被解释为范围查询。 +::: + +## 空白字符和空查询 + +空白字符不被视为运算符。如果查询字符串为空或只包含空白字符,查询不返回任何结果。 + +## 字段名称 + +在冒号前指定字段名称。下表列出了包含字段名称的示例查询。 + +`query_string` 查询中的查询 | Discover 中的查询 | 文档匹配条件 | `testindex` 索引中的匹配文档 +:--- | :--- | :--- | :--- +`title: wind` | `title: wind` | `title` 字段包含单词 `wind`。 | 1, 2 +`title: (wind OR windy)` | `title: (wind OR windy)` | `title` 字段包含单词 `wind` 或单词 `windy`。 | 1, 2, 3 +`title: \"wind rises\"` | `title: "wind rises"` | `title` 字段包含短语 `wind rises`。使用反斜杠转义引号。 | 1 +`article\\ title: wind` | `article\ title: wind` | `article title` 字段包含单词 `wind`。使用反斜杠转义空格字符。 | 4 +`title.\\*: rise` | `title.\*: rise` | 每个以 `title.` 开头的字段(在本例中为 `title.english`)都包含单词 `rise`。使用反斜杠转义通配符。 | 1 +`_exists_: description` | `_exists_: description` | 字段 `description` 存在。 | 2 + +## 通配符表达式 + +可以使用特殊字符指定通配符表达式:`?` 替代单个字符,`*` 替代零个或多个字符。 + +#### 示例 + +以下查询搜索标题包含单词 `gone` 且描述中包含以 `hist` 开头的单词的文档: + +```json +GET /testindex/_search +{ + "query": { + "query_string": { + "query": "title: gone AND description: hist*" + } + } +} +``` + +::: danger 警告 +通配符查询可能会占用大量内存,从而降低性能。位于单词开头的通配符(例如 `*cal`)开销最大,因为基于此类通配符匹配文档需要检查索引中的所有词项。要禁用前导通配符,请将 `allow_leading_wildcard` 设置为 `false`。 +::: + +为提高效率,`*` 这样的纯通配符会被重写为 `exists` 查询。因此,通配符 `description: *` 会匹配 `description` 字段为空值的文档,但不会匹配缺少 `description` 字段或该字段值为 `null` 的文档。 + +如果将 `analyze_wildcard` 设置为 `true`,OpenSearch 会分析以 `*` 结尾的查询(例如 `hist*`)。因此,OpenSearch 会根据生成的词元(Token)构建一个布尔查询:对前 n-1 个词元进行精确匹配,对最后一个词元进行前缀匹配。 + +## 正则表达式 + +要在查询字符串中指定正则表达式模式,请用正斜杠(`/`)将其括起来,例如 `title: /w[a-z]nd/`。 + +::: warning 重要 +`allow_leading_wildcard` 参数不适用于正则表达式。例如,像 `/.*d/` 这样的查询字符串会检查索引中的所有词项。 +::: + +## 模糊匹配 + +可以使用 `~` 运算符运行模糊查询,例如 `title: rise~`。 + +该查询会搜索包含与搜索词项相似(在允许的最大编辑距离之内)的词项的文档。编辑距离定义为 [Damerau-Levenshtein 距离](https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance),它衡量将一个词项变为另一个词项所需的单字符修改(插入、删除、替换或换位)次数。 + +默认编辑距离 2 应该可以捕获 80% 的拼写错误。要更改默认编辑距离,请在 `~` 运算符之后指定新的编辑距离。例如,要将编辑距离设置为 `1`,请使用查询 `title: rise~1`。 + +::: warning 重要 +不要混用模糊运算符和通配符运算符。如果同时指定模糊运算符和通配符运算符,其中一个运算符将不会生效。例如,如果搜索 `wnid*~1`,通配符运算符 `*` 会生效,但模糊运算符 `~1` 不会生效。 +::: + +## 邻近查询 + +邻近查询不要求搜索短语按指定顺序出现。它允许短语中的单词以不同顺序出现,或被其他单词隔开。邻近查询指定短语中单词的最大编辑距离。例如,以下查询在匹配指定短语中的单词时允许的编辑距离为 4: + +```json +GET /testindex/_search +{ + "query": { + "query_string": { + "query": "title: \"wind gone\"~4" + } + } +} +``` + +OpenSearch 匹配文档时,文档中单词的顺序越接近查询中指定的单词顺序(编辑距离越小),文档的相关性评分(Relevance Score)就越高。 + +## 范围 + +要为数值、字符串或日期字段指定范围,请使用方括号(`[min TO max]`)表示包含边界的范围,使用花括号(`{min TO max}`)表示不包含边界的范围。也可以混合使用方括号和花括号来包含或排除下界和上界(例如 `{min TO max]`)。 + +日期范围中的日期必须采用映射该日期字段时所用的格式。有关支持的日期格式的更多信息,请参阅[格式](/field-types/supported-field-types/date#formats)。 + +下表提供了范围语法示例。 + +数据类型 | 查询 | 查询字符串 +:--- | :--- | :--- +Numeric | 账号为 1 到 15(含)的文档。 | `account_number: [1 TO 15]` 或
`account_number: (>=1 AND <=15)` 或
`account_number: (+>=1 +<=15)` +| 账号大于或等于 15 的文档。 | `account_number: [15 TO *]` 或
`account_number: >=15`(注意 `>=` 符号后没有空格) +String | 姓氏从 Bates(含)到 Duke(不含)的文档。 | `lastname: [Bates TO Duke}` 或
`lastname: (>=Bates AND `lastname: - `OR`:字符串 `to be` 被解释为 `to OR be`
- `AND`:字符串 `to be` 被解释为 `to AND be`
默认值为 `OR`。 +`enable_position_increments` | Boolean | 为 `true` 时,生成的查询会感知位置增量。当移除停用词在词项之间留下不需要的“间隙”时,此设置很有用。默认值为 `true`。 +`fields` | String array | 要搜索的字段列表(例如 `"fields": ["title^4", "description"]`)。支持通配符。如果未指定,则默认使用 `index.query. Default_field` 设置,该设置的默认值为 `["*"]`。 +`fuzziness` | String | 在判断某个词项是否与某个值匹配时,将一个单词变为另一个单词所需的字符编辑(插入、删除、替换)次数。例如,`wined` 与 `wind` 之间的距离为 1。有效值为非负整数或 `AUTO`。默认值 `AUTO` 会根据每个词项的长度选择一个值,适用于大多数场景。 +`fuzzy_max_expansions` | Positive integer | 查询最多可以扩展到的词项数。模糊查询会“扩展到”在 `fuzziness` 指定距离内的若干个匹配词项,然后 OpenSearch 尝试匹配这些词项。默认值为 `50`。 +`fuzzy_transpositions` | Boolean | 将 `fuzzy_transpositions` 设置为 `true`(默认值)时,会在 `fuzziness` 选项的插入、删除和替换操作之外,增加相邻字符的交换操作。例如,如果 `fuzzy_transpositions` 为 true(交换“n”和“i”),`wind` 与 `wnid` 之间的距离为 1;如果为 false(删除“n”,再插入“n”),距离为 2。如果 `fuzzy_transpositions` 为 false,`rewind` 和 `wnid` 与 `wind` 的距离相同(均为 2),尽管从人的角度来看,`wnid` 显然只是一个拼写错误。默认值适用于大多数场景。 +`lenient` | Boolean | 将 `lenient` 设置为 `true` 会忽略查询与文档字段之间的数据类型不匹配。例如,查询字符串 `"8.2"` 可以匹配 `float` 类型的字段。默认值为 `false`。 +`max_determinized_states` | Positive integer | 对于包含正则表达式的查询字符串(例如 `"query": "/wind.+?/"`),Lucene 可以创建的“[状态](https://lucene.apache.org/core/8_9_0/core/org/apache/lucene/util/automaton/Operations.html#DEFAULT_MAX_DETERMINIZED_STATES)”(一种复杂度度量)的最大数量。数值越大,允许查询使用的内存越多。默认值为 10,000。 +`minimum_should_match` | Positive or negative integer, positive or negative percentage, combination | 如果查询字符串包含多个搜索词项并且使用 `or` 运算符,该参数指定文档被视为匹配时需要匹配的词项数。例如,如果 `minimum_should_match` 为 2,则 `wind often rising` 与 `The Wind Rises.` 不匹配;如果 `minimum_should_match` 为 `1`,则二者匹配。有关详细信息,请参阅 [Minimum should match](/query-dsl/minimum-should-match)。 +`phrase_slop` | Integer | 匹配的单词之间允许出现的最大单词数。如果 `phrase_slop` 为 2,则短语中匹配的单词之间最多允许出现两个单词。换位的单词的 slop 为 2。默认值为 `0`(精确短语匹配,匹配的单词必须彼此相邻)。 +`quote_analyzer` | String | 用于对查询字符串中带引号的文本进行分词的分析器。对于带引号的文本,该参数会覆盖 `analyzer` 参数。默认值为 `default_field` 指定的 `search_quote_analyzer`。 +`quote_field_suffix` | String | 此选项支持使用与非精确匹配不同的分析方法来搜索精确匹配(用引号括起来)。例如,如果 `quote_field_suffix` 为 `.exact`,并且在 `title` 字段中搜索 `\"lightly\"`,OpenSearch 会在 `title.exact` 字段中搜索单词 `lightly`。第二个字段可能使用不同的类型(例如 `keyword` 而不是 `text`)或不同的分析器。 +`rewrite` | String | 决定 OpenSearch 如何重写多词项查询并为其评分。有效值为 `constant_score`、`scoring_boolean`、`constant_score_boolean`、`top_terms_N`、`top_terms_boost_N` 和 `top_terms_blended_freqs_N`。默认值为 `constant_score`。 +`time_zone` | String | 指定目标时区相对于 `UTC` 偏移的小时数。如果查询字符串包含日期范围,则需要指明时区偏移量。例如,对于包含日期范围的查询(如 `"query": "wind rises release_date[2012-01-01 TO 2014-01-01]"`),可设置 `time_zone": "-08:00"`。用于指定偏移小时数的默认时区格式为 `UTC`。 + +::: warning 重要 +Query string 查询可能会在内部转换为[前缀查询](/query-dsl/term/prefix)。如果 [`search.allow_expensive_queries`](/query-dsl/#expensive-queries) 设置为 `false`,则不会执行前缀查询。如果启用了 `index_prefixes`,则会忽略 `search.allow_expensive_queries` 设置,并构建和执行优化后的查询。 +::: diff --git a/i18n/zh/query-dsl/full-text/simple-query-string.md b/i18n/zh/query-dsl/full-text/simple-query-string.md new file mode 100644 index 00000000..3ea72a35 --- /dev/null +++ b/i18n/zh/query-dsl/full-text/simple-query-string.md @@ -0,0 +1,351 @@ +--- +title: Simple query string +--- + +# Simple query string 查询 + +使用 `simple_query_string` 查询(Query)类型可以直接在查询字符串中指定由正则表达式分隔的多个参数。Simple query string 的语法没有 query string 严格,因为它会丢弃字符串中任何无效的部分,并且不会因语法无效而返回错误。 + +该查询使用一种[简单语法](#simple-query-string-syntax),根据特殊运算符解析查询字符串,并将字符串拆分为词项(Term)。解析完成后,查询会独立分析每个词项,然后返回匹配的文档(Document)。 + +以下查询对 `title` 字段执行模糊搜索: + +```json +GET _search +{ + "query": { + "simple_query_string": { + "query": "\"rises wind the\"~4 | *ising~2", + "fields": ["title"] + } + } +} +``` + +## Simple query string 语法 + +查询字符串由*词项*和*运算符*组成。词项是单个单词(例如,在查询 `wind rises` 中,词项为 `wind` 和 `rises`)。如果多个词项用引号括起来,它们会被视为一个短语,其中的单词按出现顺序进行匹配(例如 `"wind rises"`)。`+`、`|` 和 `-` 等运算符指定了用于解释查询字符串中文本的布尔逻辑。 + +## 运算符 + +Simple query string 语法支持以下运算符。 + +运算符 | 描述 +:--- | :--- +`+` | 作为 `AND` 运算符。 +`|` | 作为 `OR` 运算符。 +`*` | 用在词项末尾时,表示前缀查询。 +`"` | 将多个词项包装为一个短语(例如 `"wind rises"`)。 +`(`, `)` | 包装一个子句以设置优先级(例如 `wind + (rises | rising)`)。 +`~n` | 用在词项之后(例如 `wnid~3`)时,设置 `fuzziness`;用在短语之后时,设置 `slop`。 +`-` | 对词项取反。 + +上述所有运算符都是保留字符。若要将它们作为原始字符而非运算符引用,请使用反斜杠对其进行转义。发送 JSON 请求时,请使用 `\\` 转义保留字符(由于反斜杠字符本身也是保留字符,因此必须再用一个反斜杠对其进行转义)。 + +## 默认运算符 + +默认运算符为 `OR`(除非将 `default_operator` 设置为 `AND`)。默认运算符决定了查询的整体行为。例如,假设某个索引(Index)包含以下文档: + +```json +PUT /customers/_doc/1 +{ + "first_name":"Amber", + "last_name":"Duke", + "address":"880 Holmes Lane" +} +``` + +```json +PUT /customers/_doc/2 +{ + "first_name":"Hattie", + "last_name":"Bond", + "address":"671 Bristol Street" +} +``` + +```json +PUT /customers/_doc/3 +{ + "first_name":"Nanette", + "last_name":"Bates", + "address":"789 Madison St" +} +``` + +```json +PUT /customers/_doc/4 +{ + "first_name":"Dale", + "last_name":"Amber", + "address":"467 Hutchinson Court" +} +``` + +以下查询尝试查找地址中包含单词 `street` 或 `st` 且不包含单词 `madison` 的文档: + +```json +GET /customers/_search +{ + "query": { + "simple_query_string": { + "fields": [ "address" ], + "query": "street st -madison" + } + } +} + +``` + +然而,结果中不仅包含预期的文档,而是包含了全部四个文档: + +
+ + 响应 + + +```json +{ + "took": 3, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4, + "relation": "eq" + }, + "max_score": 2.2039728, + "hits": [ + { + "_index": "customers", + "_id": "2", + "_score": 2.2039728, + "_source": { + "first_name": "Hattie", + "last_name": "Bond", + "address": "671 Bristol Street" + } + }, + { + "_index": "customers", + "_id": "3", + "_score": 1.2039728, + "_source": { + "first_name": "Nanette", + "last_name": "Bates", + "address": "789 Madison St" + } + }, + { + "_index": "customers", + "_id": "1", + "_score": 1, + "_source": { + "first_name": "Amber", + "last_name": "Duke", + "address": "880 Holmes Lane" + } + }, + { + "_index": "customers", + "_id": "4", + "_score": 1, + "_source": { + "first_name": "Dale", + "last_name": "Amber", + "address": "467 Hutchinson Court" + } + } + ] + } +} +``` +
+ +由于默认运算符为 `OR`,该查询既包含含有单词 `street` 或 `st` 的文档(文档 2 和 3),也包含不含单词 `madison` 的文档(文档 1 和 4)。 + +要正确表达查询意图,请在 `-madison` 前加上 `+`: + +```json +GET /customers/_search +{ + "query": { + "simple_query_string": { + "fields": [ "address" ], + "query": "street st +-madison" + } + } +} +``` + +或者,将 `AND` 指定为默认运算符,并对单词 `street` 和 `st` 使用析取(OR): + +```json +GET /customers/_search +{ + "query": { + "simple_query_string": { + "fields": [ "address" ], + "query": "st|street -madison", + "default_operator": "AND" + } + } +} +``` + +上述查询返回文档 2: + +
+ + 响应 + + +```json +{ + "took": 2, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 2.2039728, + "hits": [ + { + "_index": "customers", + "_id": "2", + "_score": 2.2039728, + "_source": { + "first_name": "Hattie", + "last_name": "Bond", + "address": "671 Bristol Street" + } + } + ] + } +} +``` +
+ +## 限制运算符 + +要限制 simple query string 解析器支持的运算符,请在 `flags` 参数中列出希望支持的运算符,并用 `|` 分隔。例如,以下查询仅启用 `OR`、`AND` 和 `FUZZY` 运算符: + +```json +GET /customers/_search +{ + "query": { + "simple_query_string": { + "fields": [ "address" ], + "query": "bristol | madison +stre~2", + "flags": "OR|AND|FUZZY" + } + } +} +``` + +下表列出了所有可用的运算符标志。 + +标志 | 描述 +:--- | :--- +`ALL` (default) | 启用所有运算符。 +`AND` | 启用 `+`(`AND`)运算符。 +`ESCAPE` | 启用 `\` 作为转义字符。 +`FUZZY` | 启用单词之后的 `~n` 运算符,其中 `n` 是一个整数,表示匹配时允许的编辑距离。 +`NEAR` | 启用短语之后的 `~n` 运算符,其中 `n` 是匹配词元(Token)之间允许的最大位置数。与 `SLOP` 相同。 +`NONE` | 禁用所有运算符。 +`NOT` | 启用 `-`(`NOT`)运算符。 +`OR` | 启用 `|`(`OR`)运算符。 +`PHRASE` | 启用 `"`(引号)进行短语搜索。 +`PRECEDENCE` | 启用 `(` 和 `)`(括号)运算符来设置运算符优先级。 +`PREFIX` | 启用 `*`(前缀)运算符。 +`SLOP` | 启用短语之后的 `~n` 运算符,其中 `n` 是匹配词元之间允许的最大位置数。与 `NEAR` 相同。 +`WHITESPACE` | 启用空白字符作为拆分文本的字符。 + +## 通配符表达式 + +可以使用 `*` 特殊字符指定通配符表达式,它可以替代零个或多个字符。例如,以下查询在所有以 `name` 结尾的字段中进行搜索: + +```json +GET /customers/_search +{ + "query": { + "simple_query_string" : { + "query": "Amber Bond", + "fields": [ "*name" ] + } + } +} +``` + +## 权重提升 + +使用脱字符(`^`)权重提升(boost)运算符,可以按一定倍数提升某个字段的相关性评分(Relevance Score)。[0, 1) 范围内的值会降低相关性,大于 1 的值会提高相关性。默认值为 `1`。 + +例如,以下查询搜索 `first_name` 和 `last_name` 字段,并将 `first_name` 字段中的匹配结果的权重提升为 2 倍: + +```json +GET /customers/_search +{ + "query": { + "simple_query_string" : { + "query": "Amber", + "fields": [ "first_name^2", "last_name" ] + } + } +} +``` + +## 多位置词元 + +对于多位置词元,simple query string 会创建一个 [match phrase 查询](/query-dsl/full-text/match-phrase)。因此,如果将 `ml, machine learning` 指定为同义词并搜索 `ml`,OpenSearch 会搜索 `ml OR "machine learning"`。 + +或者,也可以使用合取(AND)方式匹配多位置词元。如果将 `auto_generate_synonyms_phrase_query` 设置为 `false`,OpenSearch 会搜索 `ml OR (machine AND learning)`。 + +例如,以下查询搜索文本 `ml models`,并指定不为每个同义词自动生成 match phrase 查询: + +```json +GET /testindex/_search +{ + "query": { + "simple_query_string": { + "fields": ["title"], + "query": "ml models", + "auto_generate_synonyms_phrase_query": false + } + } +} +``` + +对于该查询,OpenSearch 会创建以下布尔查询:`(ml OR (machine AND learning)) models`。 + +## 参数 + +下表列出了 `simple_query_string` 查询支持的顶级参数。除 `query` 外,所有参数均为可选。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`query`| String | 用于搜索的文本,可以包含采用 [simple query string 语法](#simple-query-string-syntax)的表达式。必需。 +`analyze_wildcard` | Boolean | 指定 OpenSearch 是否应尝试分析通配符词项。默认值为 `false`。 +`analyzer` | String | 用于对查询字符串文本进行分词的分析器(Analyzer)。默认值为 `default_field` 指定的索引时分析器。如果没有为 `default_field` 指定分析器,则 `analyzer` 为该索引的默认分析器。 +`auto_generate_synonyms_phrase_query` | Boolean | 指定是否为多词项同义词自动创建 [match_phrase 查询](/query-dsl/full-text/match)。默认值为 `true`。 +`default_operator`| String | 如果查询字符串包含多个搜索词项,该参数指定文档被视为匹配时是需要所有词项都匹配(`AND`),还是只需一个词项匹配(`OR`)。有效值为:
- `OR`:字符串 `to be` 被解释为 `to OR be`
- `AND`:字符串 `to be` 被解释为 `to AND be`
默认值为 `OR`。 +`fields` | String array | 要搜索的字段列表(例如 `"fields": ["title^4", "description"]`)。支持通配符。如果未指定,则默认使用 `index.query. Default_field` 设置,该设置的默认值为 `["*"]`。可同时搜索的最大字段数由 `indices.query.bool.max_clause_count` 定义,默认为 1,024。 +`flags` | String | 由 `|` 分隔的要启用的[标志](/query-dsl/full-text/simple-query-string)字符串(例如 `AND|OR|NOT`)。默认值为 `ALL`。你可以为 `default_field` 显式设置值。例如,要返回所有标题,可将其设置为 `"default_field": "title"`。 +`fuzzy_max_expansions` | Positive integer | 查询最多可以扩展到的词项数。模糊查询会“扩展到”在 `fuzziness` 指定距离内的若干个匹配词项,然后 OpenSearch 尝试匹配这些词项。默认值为 `50`。 +`fuzzy_transpositions` | Boolean | 将 `fuzzy_transpositions` 设置为 `true`(默认值)时,会在 `fuzziness` 选项的插入、删除和替换操作之外,增加相邻字符的交换操作。例如,如果 `fuzzy_transpositions` 为 true(交换“n”和“i”),`wind` 与 `wnid` 之间的距离为 1;如果为 false(删除“n”,再插入“n”),距离为 2。如果 `fuzzy_transpositions` 为 false,`rewind` 和 `wnid` 与 `wind` 的距离相同(均为 2),尽管从人的角度来看,`wnid` 显然只是一个拼写错误。默认值适用于大多数场景。 +`fuzzy_prefix_length`| Integer | 模糊匹配时保持不变的开头字符数。默认值为 0。 +`lenient` | Boolean | 将 `lenient` 设置为 `true` 会忽略查询与文档字段之间的数据类型不匹配。例如,查询字符串 `"8.2"` 可以匹配 `float` 类型的字段。默认值为 `false`。 +`minimum_should_match` | Positive or negative integer, positive or negative percentage, combination | 如果查询字符串包含多个搜索词项并且使用 `or` 运算符,该参数指定文档被视为匹配时需要匹配的词项数。例如,如果 `minimum_should_match` 为 2,则 `wind often rising` 与 `The Wind Rises.` 不匹配;如果 `minimum_should_match` 为 `1`,则二者匹配。有关详细信息,请参阅 [Minimum should match](/query-dsl/minimum-should-match)。 +`quote_field_suffix` | String | 此选项支持使用与非精确匹配不同的分析方法来搜索精确匹配(用引号括起来)。例如,如果 `quote_field_suffix` 为 `.exact`,并且在 `title` 字段中搜索 `\"lightly\"`,OpenSearch 会在 `title.exact` 字段中搜索单词 `lightly`。第二个字段可能使用不同的类型(例如 `keyword` 而不是 `text`)或不同的分析器。 diff --git a/i18n/zh/query-dsl/geo-and-xy/geo-bounding-box.md b/i18n/zh/query-dsl/geo-and-xy/geo-bounding-box.md new file mode 100644 index 00000000..e0e544f9 --- /dev/null +++ b/i18n/zh/query-dsl/geo-and-xy/geo-bounding-box.md @@ -0,0 +1,224 @@ +--- +title: 地理边界框 +--- + +# 地理边界框查询 + +要搜索包含 [geopoint](/field-types/supported-field-types/geo-point) 字段的文档(Document),请使用地理边界框查询(Geo-bounding Box Query)。地理边界框查询返回 geopoint 位于查询中指定的边界框内的文档。如果一个文档包含多个 geopoint,只要至少有一个 geopoint 位于边界框内,该文档就与查询匹配。 + +## 示例 + +你可以使用地理边界框查询搜索包含 geopoint 的文档。 + +创建一个映射(Mapping),将 `point` 字段映射为 `geo_point`: + +```json +PUT testindex1 +{ + "mappings": { + "properties": { + "point": { + "type": "geo_point" + } + } + } +} +``` + +将三个 geopoint 作为包含纬度和经度的对象进行索引: + +```json +PUT testindex1/_doc/1 +{ + "point": { + "lat": 74.00, + "lon": 40.71 + } +} + +PUT testindex1/_doc/2 +{ + "point": { + "lat": 72.64, + "lon": 22.62 + } +} + +PUT testindex1/_doc/3 +{ + "point": { + "lat": 75.00, + "lon": 28.00 + } +} +``` + +搜索所有文档,并过滤出点位于查询中定义的矩形内的文档: + +```json +GET testindex1/_search +{ + "query": { + "bool": { + "must": { + "match_all": {} + }, + "filter": { + "geo_bounding_box": { + "point": { + "top_left": { + "lat": 75, + "lon": 28 + }, + "bottom_right": { + "lat": 73, + "lon": 41 + } + } + } + } + } + } +} +``` + +响应中包含匹配的文档: + +```json +{ + "took" : 20, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "testindex1", + "_id" : "1", + "_score" : 1.0, + "_source" : { + "point" : { + "lat" : 74.0, + "lon" : 40.71 + } + } + } + ] + } +} +``` + +::: info 注意 +上述响应不包含 geopoint 为 `"lat": 75.00, "lon": 28.00` 的文档,这是因为 geopoint 的[精度](#precision)有限。 +::: + +## 精度 + +geopoint 坐标在索引时总是向下舍入。在查询时,边界框的上边界向下舍入,下边界向上舍入。因此,由于舍入误差,位于边界框下边缘和左边缘上的 geopoint 文档可能不会包含在结果中。另一方面,位于边界框上边缘和右边缘上的 geopoint 即使在边界之外,也可能被包含在结果中。纬度的舍入误差小于 4.20 × 10−8 度,经度的舍入误差小于 8.39 × 10−8 度(约 1 cm)。 + +## 指定边界框 + +你可以通过提供以下任一顶点坐标组合来指定边界框: + +- `top_left` 和 `bottom_right` +- `top_right` 和 `bottom_left` +- `top`、`left`、`bottom` 和 `right` + +以下示例展示了如何使用 `top`、`left`、`bottom` 和 `right` 坐标指定边界框: + +```json +GET testindex1/_search +{ + "query": { + "bool": { + "must": { + "match_all": {} + }, + "filter": { + "geo_bounding_box": { + "point": { + "top": 75, + "left": 28, + "bottom": 73, + "right": 41 + } + } + } + } + } +} +``` + +## 请求字段 + +地理边界框查询接受以下字段。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`_name` | String | 过滤器的名称。可选。 +`validation_method` | String | 验证方法。有效值为 `IGNORE_MALFORMED`(接受坐标无效的 geopoint)、`COERCE`(尝试将坐标强制转换为有效值)和 `STRICT`(坐标无效时返回错误)。默认值为 `STRICT`。 +`type` | String | 指定如何执行过滤器。有效值为 `indexed`(对过滤器建立索引)和 `memory`(在内存中执行过滤器)。默认值为 `memory`。 +`ignore_unmapped` | Boolean | 指定是否忽略未映射的字段。如果设置为 `true`,查询不会返回任何包含未映射字段的文档。如果设置为 `false`,当字段未映射时会抛出异常。默认值为 `false`。 + +## 接受的格式 + +你可以使用 geopoint 字段类型接受的任意[格式](/field-types/supported-field-types/geo-point#formats)来指定边界框顶点的坐标。 + +### 使用 geohash 指定边界框 + +如果使用 geohash 指定边界框,geohash 会被视为一个矩形。边界框的左上顶点对应 `top_left` geohash 的左上顶点,边界框的右下顶点对应 `bottom_right` geohash 的右下顶点。 + +以下示例展示了如何使用 geohash 指定与前面示例相同的边界框: + +```json +GET testindex1/_search +{ + "query": { + "bool": { + "must": { + "match_all": {} + }, + "filter": { + "geo_bounding_box": { + "point": { + "top_left": "ut7ftjkfxm34", + "bottom_right": "uuvpkcprc4rc" + } + } + } + } + } +} +``` + +要指定覆盖某个 geohash 整个区域的边界框,请将该 geohash 同时作为边界框的 `top_left` 和 `bottom_right` 参数: + +```json +GET testindex1/_search +{ + "query": { + "bool": { + "must": { + "match_all": {} + }, + "filter": { + "geo_bounding_box": { + "point": { + "top_left": "ut", + "bottom_right": "ut" + } + } + } + } + } +} +``` diff --git a/i18n/zh/query-dsl/geo-and-xy/index.md b/i18n/zh/query-dsl/geo-and-xy/index.md new file mode 100644 index 00000000..274b56a9 --- /dev/null +++ b/i18n/zh/query-dsl/geo-and-xy/index.md @@ -0,0 +1,28 @@ +--- +title: 地理和 xy 查询 +--- + +# 地理和 xy 查询 + +地理和 xy 查询(Geographic and xy Query)用于搜索包含地图或坐标平面上的点和形状的字段。地理查询作用于地理空间数据,而 xy 查询作用于二维坐标数据。在所有地理查询中,geoshape 查询与 xy 查询非常相似,区别在于前者搜索[地理字段](/field-types/supported-field-types/geographic),后者搜索[笛卡尔字段](/field-types/supported-field-types/xy)。 + +## xy 查询 + +[xy 查询](/query-dsl/geo-and-xy/xy)用于搜索在笛卡尔坐标系中包含几何图形的文档(Document)。这些几何图形可以存储在 [`xy_point`](/field-types/supported-field-types/xy-point) 字段中(支持点),也可以存储在 [`xy_shape`](/field-types/supported-field-types/xy-shape) 字段中(支持点、线、圆和多边形)。 + +xy 查询返回包含以下内容的文档: +- 与给定形状存在以下四种空间关系之一的 xy 形状和 xy 点:`INTERSECTS`、`DISJOINT`、`WITHIN` 或 `CONTAINS`。 +- 与给定形状相交的 xy 点。 + +## 地理查询 + +地理查询用于搜索包含地理空间几何图形的文档。这些几何图形可以存储在 [`geo_point`](/field-types/supported-field-types/geo-point) 字段中(支持地图上的点),也可以存储在 [`geo_shape`](/field-types/supported-field-types/geo-shape) 字段中(支持点、线、圆和多边形)。 + +OpenSearch 提供以下地理查询类型: + +- [**地理边界框查询**](/query-dsl/geo-and-xy/geo-bounding-box):返回 geopoint 字段值位于边界框内的文档。 +- **地理距离查询**:返回 geopoint 与给定 geopoint 的距离在指定范围内的文档。 +- **地理多边形查询**:返回 geopoint 位于多边形内的文档。 +- **地理形状查询**:返回包含以下内容的文档: + - 与给定形状存在以下四种空间关系之一的 geoshape 和 geopoint:`INTERSECTS`、`DISJOINT`、`WITHIN` 或 `CONTAINS`。 + - 与给定形状相交的 geopoint。 diff --git a/i18n/zh/query-dsl/geo-and-xy/xy.md b/i18n/zh/query-dsl/geo-and-xy/xy.md new file mode 100644 index 00000000..7109408b --- /dev/null +++ b/i18n/zh/query-dsl/geo-and-xy/xy.md @@ -0,0 +1,431 @@ +--- +title: xy +--- + +# xy 查询 + +要搜索包含 [xy point](/field-types/supported-field-types/xy-point) 和 [xy shape](/field-types/supported-field-types/xy-shape) 字段的文档(Document),请使用 xy 查询。 + +## 空间关系 + +当你向 xy 查询提供一个 xy 形状时,xy 字段会按照与所提供形状之间的以下空间关系进行匹配。 + +关系 | 描述 | 支持的 xy 字段类型 +:--- | :--- | :--- +`INTERSECTS` | (默认)匹配 xy point 或 xy shape 与查询中提供的形状相交的文档。 | `xy_point`, `xy_shape` +`DISJOINT` | 匹配 xy shape 与查询中提供的形状不相交的文档。 | `xy_shape` +`WITHIN` | 匹配 xy shape 完全位于查询中提供的形状之内的文档。 | `xy_shape` +`CONTAINS` | 匹配 xy shape 完全包含查询中提供的形状的文档。 | `xy_shape` + +以下示例演示如何搜索包含 xy 形状的文档。要了解如何搜索包含 xy 点的文档,请参阅[查询 xy 点](#querying-xy-points)一节。 + +## 在 xy 查询中定义形状 + +在 xy 查询中定义形状有两种方式:在查询时提供新的形状定义,或者引用在另一个索引(Index)中预先索引的形状的名称。 + +### 使用新的形状定义 + +要向 xy 查询提供新的形状,请在 `xy_shape` 字段中定义它。 + +以下示例演示如何搜索 xy 形状与查询时定义的 xy 形状匹配的文档。 + +首先,创建一个索引,并将 `geometry` 字段映射为 `xy_shape`: + +```json +PUT testindex +{ + "mappings": { + "properties": { + "geometry": { + "type": "xy_shape" + } + } + } +} +``` + +索引一个包含点的文档和一个包含多边形的文档: + +```json +PUT testindex/_doc/1 +{ + "geometry": { + "type": "point", + "coordinates": [0.5, 3.0] + } +} + +PUT testindex/_doc/2 +{ + "geometry" : { + "type" : "polygon", + "coordinates" : [ + [[2.5, 6.0], + [0.5, 4.5], + [1.5, 2.0], + [3.5, 3.5], + [2.5, 6.0]] + ] + } +} +``` + +定义一个 [`envelope`](/field-types/supported-field-types/xy-shape#envelope)—即 `[[minX, maxY], [maxX, minY]]` 格式的边界矩形。搜索 xy 点或形状与该 envelope 相交的文档: + +```json +GET testindex/_search +{ + "query": { + "xy_shape": { + "geometry": { + "shape": { + "type": "envelope", + "coordinates": [ [ 0.0, 6.0], [ 4.0, 2.0] ] + }, + "relation": "WITHIN" + } + } + } +} +``` + +下图展示了该示例。点和多边形都位于边界 envelope 之内。 + +xy shape query + +响应中包含这两个文档: + +```json +{ + "took" : 363, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 2, + "relation" : "eq" + }, + "max_score" : 0.0, + "hits" : [ + { + "_index" : "testindex", + "_id" : "1", + "_score" : 0.0, + "_source" : { + "geometry" : { + "type" : "point", + "coordinates" : [ + 0.5, + 3.0 + ] + } + } + }, + { + "_index" : "testindex", + "_id" : "2", + "_score" : 0.0, + "_source" : { + "geometry" : { + "type" : "polygon", + "coordinates" : [ + [ + [ + 2.5, + 6.0 + ], + [ + 0.5, + 4.5 + ], + [ + 1.5, + 2.0 + ], + [ + 3.5, + 3.5 + ], + [ + 2.5, + 6.0 + ] + ] + ] + } + } + } + ] + } +} +``` + +### 使用预先索引的形状定义 + +构造 xy 查询时,也可以引用在另一个索引中预先索引的形状的名称。使用这种方法,你可以在索引时定义 xy 形状,然后通过名称引用它,并在 `indexed_shape` 对象中提供以下参数。 + +参数 | 描述 +:--- | :--- +`index` | 包含预先索引的形状的索引名称。 +`id` | 包含预先索引的形状的文档的文档 ID。 +`path` | 包含预先索引的形状的字段名称(以路径形式表示)。 + +以下示例演示如何引用在另一个索引中预先索引的形状的名称。在此示例中,索引 `pre-indexed-shapes` 包含定义边界的形状,索引 `testindex` 包含需要根据这些边界检查位置的形状。 + +首先,创建索引 `pre-indexed-shapes`,并将该索引的 `geometry` 字段映射为 `xy_shape`: + +```json +PUT pre-indexed-shapes +{ + "mappings": { + "properties": { + "geometry": { + "type": "xy_shape" + } + } + } +} +``` + +索引一个指定边界的 envelope,并将其命名为 `rectangle`: + +```json +PUT pre-indexed-shapes/_doc/rectangle +{ + "geometry": { + "type": "envelope", + "coordinates" : [ [ 0.0, 6.0], [ 4.0, 2.0] ] + } +} +``` + +将一个包含点的文档和一个包含多边形的文档索引到索引 `testindex` 中: + +```json +PUT testindex/_doc/1 +{ + "geometry": { + "type": "point", + "coordinates": [0.5, 3.0] + } +} + +PUT testindex/_doc/2 +{ + "geometry" : { + "type" : "polygon", + "coordinates" : [ + [[2.5, 6.0], + [0.5, 4.5], + [1.5, 2.0], + [3.5, 3.5], + [2.5, 6.0]] + ] + } +} +``` + +使用过滤器在索引 `testindex` 中搜索形状与 `rectangle` 相交的文档: + +```json +GET testindex/_search +{ + "query": { + "bool": { + "filter": { + "xy_shape": { + "geometry": { + "indexed_shape": { + "index": "pre-indexed-shapes", + "id": "rectangle", + "path": "geometry" + } + } + } + } + } + } +} +``` + +上述查询使用默认的空间关系 `INTERSECTS`,并返回点和多边形: + +```json +{ + "took" : 26, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 2, + "relation" : "eq" + }, + "max_score" : 0.0, + "hits" : [ + { + "_index" : "testindex", + "_id" : "1", + "_score" : 0.0, + "_source" : { + "geometry" : { + "type" : "point", + "coordinates" : [ + 0.5, + 3.0 + ] + } + } + }, + { + "_index" : "testindex", + "_id" : "2", + "_score" : 0.0, + "_source" : { + "geometry" : { + "type" : "polygon", + "coordinates" : [ + [ + [ + 2.5, + 6.0 + ], + [ + 0.5, + 4.5 + ], + [ + 1.5, + 2.0 + ], + [ + 3.5, + 3.5 + ], + [ + 2.5, + 6.0 + ] + ] + ] + } + } + } + ] + } +} +``` + +## 查询 xy 点 + +你也可以使用 xy 查询搜索包含 xy 点的文档。 + +创建一个映射(Mapping),将 `point` 映射为 `xy_point`: + +```json +PUT testindex1 +{ + "mappings": { + "properties": { + "point": { + "type": "xy_point" + } + } + } +} +``` + +索引三个点: + +```json +PUT testindex1/_doc/1 +{ + "point": "1.0, 1.0" +} + +PUT testindex1/_doc/2 +{ + "point": "2.0, 0.0" +} + +PUT testindex1/_doc/3 +{ + "point": "-2.0, 2.0" +} +``` + +搜索位于以 (0, 0) 为圆心、半径为 2 的圆内的点: + +```json +GET testindex1/_search +{ + "query": { + "xy_shape": { + "point": { + "shape": { + "type": "circle", + "coordinates": [0.0, 0.0], + "radius": 2 + } + } + } + } +} +``` + +::: info 注意 +xy point 只支持默认的 `INTERSECTS` 空间关系,因此无需提供 `relation` 参数。 +::: + +下图展示了该示例。点 1 和点 2 位于圆内,点 3 位于圆外。 + +xy point query + +响应返回文档 1 和文档 2: + +```json +{ + "took" : 575, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 2, + "relation" : "eq" + }, + "max_score" : 0.0, + "hits" : [ + { + "_index" : "testindex1", + "_id" : "1", + "_score" : 0.0, + "_source" : { + "point" : "1.0, 1.0" + } + }, + { + "_index" : "testindex1", + "_id" : "2", + "_score" : 0.0, + "_source" : { + "point" : "2.0, 0.0" + } + } + ] + } +} +``` diff --git a/i18n/zh/query-dsl/index.md b/i18n/zh/query-dsl/index.md new file mode 100644 index 00000000..697fdb1b --- /dev/null +++ b/i18n/zh/query-dsl/index.md @@ -0,0 +1,99 @@ +--- +title: Query DSL +--- + +# Query DSL + +OpenSearch 提供了一种名为 *查询领域特定语言(Query Domain-Specific Language,DSL)* 的搜索语言,你可以用它来搜索数据。Query DSL 是一种灵活的语言,采用 JSON 接口。 + +使用 Query DSL 时,需要在搜索的 `query` 参数中指定查询(Query)。OpenSearch 中最简单的搜索之一是使用 `match_all` 查询,它会匹配索引(Index)中的所有文档(Document): + +```json +GET testindex/_search +{ + "query": { + "match_all": { + } + } +} +``` + +一个查询可以由多个查询子句组成。你可以组合查询子句来构造复杂的查询。 + +总体而言,查询可以分为两类——*叶查询(Leaf Query)* 和 *复合查询(Compound Query)*: + +- **叶查询**:叶查询在某个或某些字段中搜索指定的值。叶查询可以单独使用,包括以下查询类型: + + - [全文查询](/query-dsl/full-text/):使用全文查询(Full-text Query)搜索文本文档。对于经过分析的文本字段,全文查询会使用索引该字段时所用的同一个分析器(Analyzer)将查询字符串拆分为词项。对于精确值搜索,全文查询会查找指定的值,而不进行文本分析。 + + - [词项级查询](/query-dsl/term/):使用词项级查询(Term-level Query)在文档中搜索精确的词项,例如 ID 或值范围。词项级查询不会分析搜索词项,也不会按相关性评分(Relevance Score)对结果排序。 + + - [地理和 xy 查询](/query-dsl/geo-and-xy/):使用地理查询搜索包含地理数据的文档。使用 xy 查询搜索包含二维坐标系中的点和形状的文档。 + + - 连接查询:使用连接查询搜索嵌套字段,或返回与特定查询匹配的父文档和子文档。连接查询的类型包括 `nested`、`has_child`、`has_parent` 和 `parent_id` 查询。 + + - [跨度查询](/query-dsl/span-query):使用跨度查询(Span Query)执行精确的位置搜索。跨度查询是底层的特定查询,可以控制指定查询词项的顺序和邻近程度。它们主要用于搜索法律文档。 + + - [专用查询](/query-dsl/specialized/):专用查询包括所有其他查询类型(`distance_feature`、`more_like_this`、`percolate`、`rank_feature`、`script`、`script_score` 和 `wrapper`)。 + +- **复合查询**:复合查询是多个叶子句或复合子句的包装器,用于组合它们的结果或修改它们的行为。复合查询包括 Boolean、disjunction max、constant score、function score 和 boosting 查询类型。更多信息,请参阅[复合查询](/query-dsl/compound/)。 + +## 关于文本字段中的 Unicode 特殊字符 + +由于 Unicode 特殊字符会形成词边界,当 [text 字段类型](/field-types/supported-field-types/text)的值包含这类特殊字符时,Unicode 标准分析器无法将其作为一个完整的值进行索引。因此,包含特殊字符的 text 字段值会被标准分析器解析为以该特殊字符分隔的多个值,实际上就是把特殊字符两侧的不同部分分别切分成词元。这可能导致文档被意外过滤,并可能削弱对文档访问的控制。 + +以下示例展示了包含特殊字符、会被标准分析器错误解析的值。在此示例中,值中的连字符/减号导致分析器无法区分 `user.id` 的两个不同用户,而将它们视为同一个用户: + +```json +{ + "bool": { + "must": { + "match": { + "user.id": "User-1" + } + } + } +} +``` + +```json +{ + "bool": { + "must": { + "match": { + "user.id": "User-2" + } + } + } +} +``` + +为了在使用 Query DSL 或 REST API 时避免这种情况,你可以使用自定义分析器,或者将字段映射为 `keyword`,以执行精确匹配搜索。关于后一种方式,请参阅 [Keyword 字段类型](/field-types/supported-field-types/keyword)。 + +关于使用 `text` 字段类型时应避免的字符列表,请参阅 [Word Boundaries](https://unicode.org/reports/tr29/#Word_Boundaries)。 + +## 开销较大的查询 + +开销较大的查询(Expensive Query)可能会消耗大量内存,导致集群性能下降。以下查询可能会消耗较多资源: + +- [`fuzzy`](/query-dsl/term/fuzzy) 查询 +- [`prefix`](/query-dsl/term/prefix) 查询 +- 针对 [`text`](/field-types/supported-field-types/text) 和 [`keyword`](/field-types/supported-field-types/keyword) 字段的 [`range`](/query-dsl/term/range) 查询 +- [`regexp`](/query-dsl/term/regexp) 查询 +- [`wildcard`](/query-dsl/term/wildcard) 查询 +- 在内部被转换为前缀查询的 [`query_string`](/query-dsl/full-text/query-string) 查询 + +要禁止开销较大的查询,可以按如下方式禁用 `search.allow_expensive_queries` 集群设置: + +```json +PUT _cluster/settings +{ + "persistent": { + "search.allow_expensive_queries": false + } +} +``` + +::: tip 提示 +要跟踪开销较大的查询,请启用[分片慢日志](/install-and-configure/configuring-opensearch/logs#shard-slow-logs)。 +::: diff --git a/i18n/zh/query-dsl/match-all.md b/i18n/zh/query-dsl/match-all.md new file mode 100644 index 00000000..0ec65e39 --- /dev/null +++ b/i18n/zh/query-dsl/match-all.md @@ -0,0 +1,27 @@ +--- +title: Match all 查询 +--- + +# Match all 查询 + +`match_all` 查询返回所有文档(Document)。如果需要返回整个文档集,该查询在测试大型文档集时会很有用。 + +```json +GET _search +{ + "query": { + "match_all": {} + } +} +``` + +`match_all` 查询有一个对应的 `match_none` 查询,但它很少用到: + +```json +GET _search +{ + "query": { + "match_none": {} + } +} +``` diff --git a/i18n/zh/query-dsl/minimum-should-match.md b/i18n/zh/query-dsl/minimum-should-match.md new file mode 100644 index 00000000..b33ac98b --- /dev/null +++ b/i18n/zh/query-dsl/minimum-should-match.md @@ -0,0 +1,438 @@ +--- +title: Minimum should match +--- + +# Minimum should match + +`minimum_should_match` 参数可用于全文搜索,它指定文档必须匹配的最少词项数,只有满足该数量的文档才会在搜索结果中返回。 + +以下示例要求文档至少匹配三个搜索词项中的两个,才会作为搜索结果返回: + +```json +GET /shakespeare/_search +{ + "query": { + "match": { + "text_entry": { + "query": "prince king star", + "minimum_should_match": "2" + } + } + } +} +``` + +在此示例中,查询包含三个通过 `OR` 组合的可选子句,因此文档必须匹配 `prince`、`king` 或 `star`。 + +## 有效值 + +你可以将 `minimum_should_match` 参数指定为以下值之一。 + +值类型 | 示例 | 描述 +:--- | :--- | :--- +非负整数 | `2` | 文档必须匹配此数量的可选子句。 +负整数 | `-1` | 文档必须匹配的可选子句数量为可选子句总数减去此数值。 +非负百分比 | `70%` | 文档必须匹配可选子句总数的此百分比。需要匹配的子句数量会向下取整到最接近的整数。 +负百分比 | `-30%` | 文档可以有可选子句总数的此百分比不匹配。允许文档不匹配的子句数量会向下取整到最接近的整数。 +组合 | `2<75%` | 采用 `n + +使用 `neural_sparse` 查询在[神经稀疏搜索](/search-plugins/neural-sparse-search)中进行向量字段搜索。 + +## 请求字段 + +在 `neural_sparse` 查询中包含以下请求字段: + +```json +"neural_sparse": { + "": { + "query_text": "", + "model_id": "" + } +} +``` + +顶层的 `vector_field` 指定要对其运行搜索查询的向量字段。下表列出了其他 `neural_sparse` 查询字段。 + +字段 | 数据类型 | 必需/可选 | 描述 +:--- | :--- | :--- +`query_text` | String | 必需 | 用于生成向量嵌入的查询文本。 +`model_id` | String | 必需 | 用于从查询文本生成向量嵌入的稀疏编码模型或分词器(Tokenizer)模型的 ID。模型必须先部署到 OpenSearch 中,才能用于稀疏神经搜索。更多信息,请参阅[在 OpenSearch 中使用自定义模型](/ml-commons-plugin/using-ml-models)和[神经稀疏搜索](/search-plugins/neural-sparse-search)。 +`max_token_score` | Float | 可选 | (已弃用)词汇表中所有词元(Token)评分的理论上限(用于性能优化)。对于 OpenSearch 提供的[预训练稀疏嵌入模型](/ml-commons-plugin/pretrained-models#sparse-encoding-models),我们建议将 `amazon/neural-sparse/opensearch-neural-sparse-encoding-doc-v1` 的 `max_token_score` 设置为 2,将 `amazon/neural-sparse/opensearch-neural-sparse-encoding-v1` 的设置为 3.5。该字段从 OpenSearch 2.12 起已弃用。 + +#### 示例请求 + +```json +GET my-nlp-index/_search +{ + "query": { + "neural_sparse": { + "passage_embedding": { + "query_text": "Hi world", + "model_id": "aP2Q8ooBpBj3wT4HVS8a" + } + } + } +} +``` diff --git a/i18n/zh/query-dsl/specialized/neural.md b/i18n/zh/query-dsl/specialized/neural.md new file mode 100644 index 00000000..9546ba21 --- /dev/null +++ b/i18n/zh/query-dsl/specialized/neural.md @@ -0,0 +1,68 @@ +--- +title: Neural +--- + +# Neural 查询 + +使用 `neural` 查询在[神经搜索](/search-plugins/neural-search)中进行向量字段搜索。 + +## 请求字段 + +在 `neural` 查询中包含以下请求字段: + +```json +"neural": { + "": { + "query_text": "", + "query_image": "", + "model_id": "", + "k": 100 + } +} +``` + +顶层的 `vector_field` 指定要对其运行搜索查询的向量字段。下表列出了其他 neural 查询字段。 + +字段 | 数据类型 | 必需/可选 | 描述 +:--- | :--- | :--- +`query_text` | String | 可选 | 用于生成向量嵌入的查询文本。`query_text` 和 `query_image` 至少要指定一个。 +`query_image` | String | 可选 | 与查询图像对应的 base-64 编码字符串,用于生成向量嵌入。`query_text` 和 `query_image` 至少要指定一个。 +`model_id` | String | 如果未设置默认模型 ID,则为必需。更多信息,请参阅[为索引或字段设置默认模型](/search-plugins/semantic-search#setting-a-default-model-on-an-index-or-field)。 | 用于从查询文本生成向量嵌入的模型的 ID。模型必须先部署到 OpenSearch 中,才能用于神经搜索。更多信息,请参阅[在 OpenSearch 中使用自定义模型](/ml-commons-plugin/using-ml-models)和[神经搜索](/search-plugins/neural-search)。 +`k` | Integer | 可选 | k-NN 搜索返回的结果数量。默认值为 10。 +`filter` | Object | 可选 | 用于减少待考虑文档数量的查询。关于过滤器用法的更多信息,请参阅[使用过滤器的 k-NN 搜索](/search-plugins/knn/filter-search-knn)。**重要**:过滤器只能与 `faiss` 或 `lucene` 引擎配合使用。 + +#### 示例请求 + +```json +GET /my-nlp-index/_search +{ + "query": { + "neural": { + "passage_embedding": { + "query_text": "Hi world", + "query_image": "iVBORw0KGgoAAAAN...", + "k": 100, + "filter": { + "bool": { + "must": [ + { + "range": { + "rating": { + "gte": 8, + "lte": 10 + } + } + }, + { + "term": { + "parking": "true" + } + } + ] + } + } + } + } + } +} +``` diff --git a/i18n/zh/query-dsl/specialized/script-score.md b/i18n/zh/query-dsl/specialized/script-score.md new file mode 100644 index 00000000..06126230 --- /dev/null +++ b/i18n/zh/query-dsl/specialized/script-score.md @@ -0,0 +1,366 @@ +--- +title: Script score +--- + +# Script score 查询 + +使用 `script_score` 查询可以通过脚本自定义评分计算方式。对于开销较大的评分函数,可以使用 `script_score` 查询只为经过过滤后返回的文档(Document)计算评分。 + +## 示例 + +例如,以下请求创建一个包含一个文档的索引(Index): + +```json +PUT testindex1/_doc/1 +{ + "name": "John Doe", + "multiplier": 0.5 +} +``` + +你可以使用 `match` 查询返回 `name` 字段中包含 `John` 的所有文档: + +```json +GET testindex1/_search +{ + "query": { + "match": { + "name": "John" + } + } +} +``` + +在响应中,文档 1 的评分为 `0.2876821`: + +```json +{ + "took": 7, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.2876821, + "hits": [ + { + "_index": "testindex1", + "_id": "1", + "_score": 0.2876821, + "_source": { + "name": "John Doe", + "multiplier": 0.5 + } + } + ] + } +} +``` + +现在,我们使用一个脚本来更改文档评分,该脚本将评分计算为 `_score` 字段的值乘以 `multiplier` 字段的值。在以下查询中,可以通过 `_score` 变量访问文档当前的相关性评分(Relevance Score),并通过 `doc['multiplier'].value` 访问 `multiplier` 的值: + +```json +GET testindex1/_search +{ + "query": { + "script_score": { + "query": { + "match": { + "name": "John" + } + }, + "script": { + "source": "_score * doc['multiplier'].value" + } + } + } +} +``` + +在响应中,文档 1 的评分是原始评分的一半: + +```json +{ + "took": 8, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.14384104, + "hits": [ + { + "_index": "testindex1", + "_id": "1", + "_score": 0.14384104, + "_source": { + "name": "John Doe", + "multiplier": 0.5 + } + } + ] + } +} +``` + +## 参数 + +`script_score` 查询支持以下顶层参数。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`query` | Object | 用于搜索的查询。必需。 +`script` | Object | 用于计算 `query` 返回的文档评分的脚本。必需。 +`min_score` | Float | 从结果中排除评分低于 `min_score` 的文档。可选。 +`boost` | Float | 按给定的倍数提升文档评分。小于 1.0 的值会降低相关性,大于 1.0 的值会提高相关性。默认值为 1.0。 + +::: warning 重要 +`script_score` 查询计算出的相关性评分不能为负数。 +::: + +## 使用内置函数自定义评分计算 + +要自定义评分计算,可以使用某个内置的 Painless 函数。对于每个函数,OpenSearch 都提供了一个或多个可以在 script score 上下文中访问的 Painless 方法。你可以直接调用以下各节中列出的 Painless 方法,而无需使用类名或实例名限定符。 + +### Saturation + +saturation 函数按 `score = value /(value + pivot)` 计算饱和度,其中 `value` 是字段值,`pivot` 的选取应使得当 `value` 大于 `pivot` 时评分大于 0.5,当 `value` 小于 `pivot` 时评分小于 0.5。评分位于 (0, 1) 范围内。要应用 saturation 函数,请调用以下 Painless 方法: + +- `double saturation(double , double )` + +#### 示例 {#example-1} + +以下示例查询在 `articles` 索引中搜索文本 `neural search`。它将文档的原始相关性评分与 `article_rank` 值相结合,其中 `article_rank` 值先经过 saturation 函数转换: + +```json +GET articles/_search +{ + "query": { + "script_score": { + "query": { + "match": { "article_name": "neural search" } + }, + "script" : { + "source" : "_score + saturation(doc['article_rank'].value, 11)" + } + } + } +} +``` + +### Sigmoid + +与 saturation 函数类似,sigmoid 函数按 `score = value^exp/ (value^exp + pivot^exp)` 计算评分,其中 `value` 是字段值,`exp` 是指数缩放因子,`pivot` 的选取应使得当 `value` 大于 `pivot` 时评分大于 0.5,当 `value` 小于 `pivot` 时评分小于 0.5。要应用 sigmoid 函数,请调用以下 Painless 方法: + +- `double sigmoid(double , double , double )` + +#### 示例 {#example-2} + +以下示例查询在 `articles` 索引中搜索文本 `neural search`。它将文档的原始相关性评分与 `article_rank` 值相结合,其中 `article_rank` 值先经过 sigmoid 函数转换: + +```json +GET articles/_search +{ + "query": { + "script_score": { + "query": { + "match": { "article_name": "neural search" } + }, + "script" : { + "source" : "_score + sigmoid(doc['article_rank'].value, 11, 2)" + } + } + } +} +``` + +### Random score + +random score 函数生成在 [0, 1) 范围内均匀分布的随机评分。要了解该函数的工作原理,请参阅 [random score 函数](/query-dsl/compound/function-score#the-random-score-function)。要应用 random score 函数,请调用以下 Painless 方法之一: + +- `double randomScore(int )`:使用 Lucene 内部文档 ID 作为种子值。 +- `double randomScore(int , String )` + +#### 示例 {#example-3} + +以下查询使用带有 `seed` 和 `field` 的 `random_score` 函数: + +```json +GET articles/_search +{ + "query": { + "script_score": { + "query": { + "match": { "article_name": "neural search" } + }, + "script" : { + "source" : "randomScore(20, '_seq_no')" + } + } + } +} +``` + +### 衰减函数 + +使用衰减函数(Decay Function),可以根据距离远近或时间新旧为结果评分。更多信息,请参阅[衰减函数](/query-dsl/compound/function-score#decay-functions)。你可以使用指数、高斯或线性衰减曲线计算评分。要应用衰减函数,请根据字段类型调用以下 Painless 方法之一: + +- [数值](/field-types/supported-field-types/numeric)字段: + - `double decayNumericGauss(double , double , double , double , double )` + - `double decayNumericExp(double , double , double , double , double )` + - `double decayNumericLinear(double , double , double , double , double )` +- [Geopoint](/field-types/supported-field-types/geo-point) 字段: + - `double decayGeoGauss(String , String , String , double , GeoPoint )` + - `double decayGeoExp(String , String , String , double , GeoPoint )` + - `double decayGeoLinear(String , String , String , double , GeoPoint )` +- [日期](/field-types/supported-field-types/date)字段: + - `double decayDateGauss(String , String , String , double , JodaCompatibleZonedDateTime )` + - `double decayDateExp(String , String , String , double , JodaCompatibleZonedDateTime )` + - `double decayDateLinear(String , String , String , double , JodaCompatibleZonedDateTime )` + +#### 示例:数值字段 + +以下查询对数值字段使用指数衰减函数: + +```json +GET articles/_search +{ + "query": { + "script_score": { + "query": { + "match": { + "article_name": "neural search" + } + }, + "script": { + "source": "decayNumericExp(params.origin, params.scale, params.offset, params.decay, doc['article_rank'].value)", + "params": { + "origin": 50, + "scale": 20, + "offset": 30, + "decay": 0.5 + } + } + } + } +} +``` + +#### 示例:Geopoint 字段 + +以下查询对 geopoint 字段使用高斯衰减函数: + +```json +GET hotels/_search +{ + "query": { + "script_score": { + "query": { + "match": { + "name": "hotel" + } + }, + "script": { + "source": "decayGeoGauss(params.origin, params.scale, params.offset, params.decay, doc['location'].value)", + "params": { + "origin": "40.71,74.00", + "scale": "300ft", + "offset": "200ft", + "decay": 0.25 + } + } + } + } +} +``` + +#### 示例:日期字段 + +以下查询对日期字段使用线性衰减函数: + +```json +GET blogs/_search +{ + "query": { + "script_score": { + "query": { + "match": { + "name": "opensearch" + } + }, + "script": { + "source": "decayDateLinear(params.origin, params.scale, params.offset, params.decay, doc['date_posted'].value)", + "params": { + "origin": "2022-04-24", + "scale": "6d", + "offset": "1d", + "decay": 0.25 + } + } + } + } +} +``` + +### 词频函数 + +词频函数(Term Frequency Function)在评分脚本源代码中公开词项级统计信息。你可以使用这些统计信息实现自定义的信息检索和排名算法,例如在查询时按热度对评分进行乘法或加法权重提升(boost)。要应用词频函数,请调用以下 Painless 方法之一: + +- `int termFreq(String , String )`:获取特定词项在字段中的词频。 +- `long totalTermFreq(String , String )`:获取特定词项在字段中的总词频。 +- `long sumTotalTermFreq(String )`:获取字段中所有总词频之和。 + +#### 示例 {#example-4} + +以下查询将评分计算为 `fields` 列表中每个字段的总词频乘以 `multiplier` 值: + +```json +GET /demo_index_v1/_search +{ + "query": { + "function_score": { + "query": { + "match_all": {} + }, + "script_score": { + "script": { + "source": """ + for (int x = 0; x < params.fields.length; x++) { + String field = params.fields[x]; + if (field != null) { + return params.multiplier * totalTermFreq(field, params.term); + } + } + return params.default_value; + + """, + "params": { + "fields": ["title", "description"], + "term": "ai", + "multiplier": 2, + "default_value": 1 + } + } + } + } + } +} +``` + +::: warning 重要 +如果 [`search.allow_expensive_queries`](/query-dsl/#expensive-queries) 设置为 `false`,则不会执行 `script_score` 查询。 +::: diff --git a/i18n/zh/query-dsl/term-vs-full-text.md b/i18n/zh/query-dsl/term-vs-full-text.md new file mode 100644 index 00000000..61057c40 --- /dev/null +++ b/i18n/zh/query-dsl/term-vs-full-text.md @@ -0,0 +1,231 @@ +--- +title: 词项级查询与全文查询的比较 +--- + +# 词项级查询与全文查询的比较 + +词项级查询(Term-level Query)和全文查询(Full-text Query)都可以用来搜索文本,但词项级查询通常用于搜索结构化数据,而全文查询用于全文搜索。词项级查询与全文查询的主要区别在于:词项级查询在文档(Document)中搜索指定的精确词项,而全文查询会对查询字符串进行[分析](/analyzers/)。下表总结了词项级查询与全文查询之间的区别。 + +| | 词项级查询 | 全文查询 +:--- | :--- | :--- +*描述* | 词项级查询回答哪些文档与查询匹配。 | 全文查询回答文档与查询的匹配程度。 +*分析器* | 搜索词项不会被分析。也就是说,term 查询会按原样搜索你的搜索词项。 | 搜索词项会被索引特定文档字段时所用的同一个分析器(Analyzer)分析。也就是说,你的搜索词项会经历与文档字段相同的分析过程。 +*相关性* | 词项级查询只返回匹配的文档,而不按相关性评分(Relevance Score)对其排序。它们仍然会计算相关性评分,但返回的所有文档的评分都相同。 | 全文查询会为每个匹配项计算相关性评分,并按相关性从高到低对结果排序。 +*使用场景* | 当你需要匹配数字、日期或标签等精确值,且不需要按相关性对匹配结果排序时,请使用词项级查询。 | 当你需要匹配文本字段,并在考虑大小写和词干变体等因素后按相关性排序时,请使用全文查询。 + +::: info 注意 +OpenSearch 使用 BM25 排名算法计算相关性评分。更多信息,请参阅 [Okapi BM25](https://en.wikipedia.org/wiki/Okapi_BM25)。 +::: + +## 应该使用全文查询还是词项级查询? + +为了阐明全文查询与词项级查询之间的区别,请看以下两个搜索特定文本短语的示例。莎士比亚全集已被索引到一个 OpenSearch 集群中。 + +### 示例:短语搜索 + +在此示例中,你将在莎士比亚全集的 `text_entry` 字段中搜索短语「To be, or not to be」。 + +首先,使用**词项级查询**进行此搜索: + +```json +GET shakespeare/_search +{ + "query": { + "term": { + "text_entry": "To be, or not to be" + } + } +} +``` + +响应中没有任何匹配项,`hits` 为零即说明了这一点: + +```json +{ + "took" : 3, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 0, + "relation" : "eq" + }, + "max_score" : null, + "hits" : [ ] + } +} +``` + +这是因为词项「To be, or not to be」是在倒排索引中按字面搜索的,而倒排索引中只存储了文本字段经过分析后的值。词项级查询不适合搜索经过分析的文本字段,因为它们经常会产生意外的结果。处理文本数据时,词项级查询只应用于映射为 `keyword` 的字段。 + +现在,使用**全文查询**搜索同一短语: + +```json +GET shakespeare/_search +{ + "query": { + "match": { + "text_entry": "To be, or not to be" + } + } +} +``` + +搜索查询「To be, or not to be」会像文档的 `text_entry` 字段一样,经过分析并被切分为词元(Token)数组。全文查询会取搜索查询与所有文档的 `text_entry` 字段之间的词元交集,然后按相关性评分对结果排序: + +```json +{ + "took" : 19, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 10000, + "relation" : "gte" + }, + "max_score" : 17.419369, + "hits" : [ + { + "_index" : "shakespeare", + "_id" : "34229", + "_score" : 17.419369, + "_source" : { + "type" : "line", + "line_id" : 34230, + "play_name" : "Hamlet", + "speech_number" : 19, + "line_number" : "3.1.64", + "speaker" : "HAMLET", + "text_entry" : "To be, or not to be: that is the question:" + } + }, + { + "_index" : "shakespeare", + "_id" : "109930", + "_score" : 14.883024, + "_source" : { + "type" : "line", + "line_id" : 109931, + "play_name" : "A Winters Tale", + "speech_number" : 23, + "line_number" : "4.4.153", + "speaker" : "PERDITA", + "text_entry" : "Not like a corse; or if, not to be buried," + } + }, + { + "_index" : "shakespeare", + "_id" : "103117", + "_score" : 14.782743, + "_source" : { + "type" : "line", + "line_id" : 103118, + "play_name" : "Twelfth Night", + "speech_number" : 53, + "line_number" : "1.3.95", + "speaker" : "SIR ANDREW", + "text_entry" : "will not be seen; or if she be, its four to one" + } + } + ] + } +} +... +``` + +关于所有全文查询的列表,请参阅[全文查询](/query-dsl/full-text/)。 + +### 示例:精确词项搜索 + +如果你想在 `speaker` 字段中搜索「HAMLET」这样的精确词项,并且不需要按相关性评分对结果排序,那么词项级查询的效率更高: + +```json +GET shakespeare/_search +{ + "query": { + "term": { + "speaker": "HAMLET" + } + } +} +``` + +响应中包含匹配的文档: + +```json +{ + "took" : 5, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 1582, + "relation" : "eq" + }, + "max_score" : 4.2540946, + "hits" : [ + { + "_index" : "shakespeare", + "_id" : "32700", + "_score" : 4.2540946, + "_source" : { + "type" : "line", + "line_id" : 32701, + "play_name" : "Hamlet", + "speech_number" : 9, + "line_number" : "1.2.66", + "speaker" : "HAMLET", + "text_entry" : "[Aside] A little more than kin, and less than kind." + } + }, + { + "_index" : "shakespeare", + "_id" : "32702", + "_score" : 4.2540946, + "_source" : { + "type" : "line", + "line_id" : 32703, + "play_name" : "Hamlet", + "speech_number" : 11, + "line_number" : "1.2.68", + "speaker" : "HAMLET", + "text_entry" : "Not so, my lord; I am too much i' the sun." + } + }, + { + "_index" : "shakespeare", + "_id" : "32709", + "_score" : 4.2540946, + "_source" : { + "type" : "line", + "line_id" : 32710, + "play_name" : "Hamlet", + "speech_number" : 13, + "line_number" : "1.2.75", + "speaker" : "HAMLET", + "text_entry" : "Ay, madam, it is common." + } + } + ] + } +} +... +``` + +词项级查询提供精确匹配。因此,如果你搜索「Hamlet」,不会得到任何匹配项,因为「HAMLET」是一个 keyword 字段,在 OpenSearch 中按字面存储,而不是以经过分析的形式存储。 +搜索查询「HAMLET」同样按字面进行搜索。因此,要匹配该字段,我们需要输入完全相同的字符。 diff --git a/i18n/zh/query-dsl/term/exists.md b/i18n/zh/query-dsl/term/exists.md new file mode 100644 index 00000000..a60f8252 --- /dev/null +++ b/i18n/zh/query-dsl/term/exists.md @@ -0,0 +1,140 @@ +--- +title: Exists +--- + +# Exists 查询 + +使用 `exists` 查询搜索包含特定字段的文档(Document)。 + +在以下任一情况下,文档字段不存在已索引的值: + +- 映射(Mapping)中为该字段指定了 `"index" : false`。 +- 源 JSON 中该字段为 `null` 或 `[]`。 +- 字段值的长度超过了映射中的 `ignore_above` 设置。 +- 字段值格式错误,且映射中定义了 `ignore_malformed`。 + +在以下任一情况下,文档字段存在已索引的值: + +- 该值是一个数组,其中包含一个或多个 null 元素以及一个或多个非 null 元素(例如 `["one", null]`)。 +- 该值是空字符串(`""` 或 `"-"`)。 +- 该值是字段映射中定义的自定义 `null_value`。 + +## 示例 + +例如,假设一个索引(Index)包含以下两个文档: + +```json +PUT testindex/_doc/1 +{ + "title": "The wind rises" +} +``` + +```json +PUT testindex/_doc/2 +{ + "title": "Gone with the wind", + "description": "A 1939 American epic historical film" +} +``` + +以下查询搜索包含 `description` 字段的文档: + +```json +GET testindex/_search +{ + "query": { + "exists": { + "field": "description" + } + } +} +``` + +响应中包含匹配的文档: + +```json +{ + "took": 3, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "testindex", + "_id": "2", + "_score": 1, + "_source": { + "title": "Gone with the wind", + "description": "A 1939 American epic historical film" + } + } + ] + } +} +``` + +## 查找缺少已索引值的文档 + +要查找缺少已索引值的文档,可以使用带有内部 `exists` 查询的 `must_not` [Boolean 查询](/query-dsl/compound/bool)。例如,以下请求搜索缺少 `description` 字段的文档: + +```json +GET testindex/_search +{ + "query": { + "bool": { + "must_not": { + "exists": { + "field": "description" + } + } + } + } +} +``` + +响应中包含匹配的文档: + +```json +{ + "took": 19, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0, + "hits": [ + { + "_index": "testindex", + "_id": "1", + "_score": 0, + "_source": { + "title": "The wind rises" + } + } + ] + } +} +``` + +## 参数 + +该查询接受字段名称(``)作为顶层参数。 diff --git a/i18n/zh/query-dsl/term/fuzzy.md b/i18n/zh/query-dsl/term/fuzzy.md new file mode 100644 index 00000000..0213a799 --- /dev/null +++ b/i18n/zh/query-dsl/term/fuzzy.md @@ -0,0 +1,88 @@ +--- +title: Fuzzy +--- + +# Fuzzy 查询 + +模糊查询(Fuzzy Query)搜索包含与搜索词项相似(在允许的最大 [Levenshtein 距离](https://en.wikipedia.org/wiki/Levenshtein_distance)内)的词项的文档(Document)。Levenshtein 距离衡量将一个词项变为另一个词项所需的单字符修改次数。这些修改包括: + +- 替换:**c**at 变为 **b**at +- 插入:cat 变为 cat**s** +- 删除:**c**at 变为 at +- 换位:**ca**t 变为 **ac**t + +模糊查询会创建一个列表,其中包含搜索词项在 Levenshtein 距离范围内所有可能的扩展。你可以在 `max_expansions` 字段中指定此类扩展的最大数量。然后,它会搜索与任一扩展匹配的文档。 + +以下示例查询搜索说话人 `HALET`(`HAMLET` 的拼写错误)。由于未指定最大编辑距离,因此使用默认的 `AUTO` 编辑距离: + +```json +GET shakespeare/_search +{ + "query": { + "fuzzy": { + "speaker": { + "value": "HALET" + } + } + } +} +``` + +响应中包含说话人为 `HAMLET` 的所有文档。 + +以下示例查询使用高级参数搜索单词 `HALET`: + +```json +GET shakespeare/_search +{ + "query": { + "fuzzy": { + "speaker": { + "value": "HALET", + "fuzziness": "2", + "max_expansions": 40, + "prefix_length": 0, + "transpositions": true, + "rewrite": "constant_score" + } + } + } +} +``` + +## 参数 + +该查询接受字段名称(``)作为顶层参数: + +```json +GET _search +{ + "query": { + "fuzzy": { + "": { + "value": "sample", + ... + } + } + } +} +``` + +`` 接受以下参数。除 `value` 外,所有参数均为可选。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`value` | String | 要在 `` 指定的字段中搜索的词项。 +`fuzziness` | `AUTO`, `0`, or a positive integer | 在判断词项是否与值匹配时,将一个单词变为另一个单词所需的字符编辑(插入、删除、替换)次数。例如,`wined` 与 `wind` 之间的距离为 1。默认值 `AUTO` 会根据每个词项的长度选择一个值,适用于大多数使用场景。 +`max_expansions` | Positive integer | 查询可以扩展到的最大词项数量。模糊查询会「扩展到」若干个在 `fuzziness` 指定距离内的匹配词项,然后 OpenSearch 尝试匹配这些词项。默认值为 `50`。 +`prefix_length` | Non-negative integer | 不参与模糊匹配的前导字符数量。默认值为 `0`。 +`rewrite` | String | 决定 OpenSearch 如何重写多词项查询并为其评分。有效值为 `constant_score`、`scoring_boolean`、`constant_score_boolean`、`top_terms_N`、`top_terms_boost_N` 和 `top_terms_blended_freqs_N`。默认值为 `constant_score`。 +`transpositions` | Boolean | 指定是否允许将两个相邻字符的换位(`ab` 变为 `ba`)视为一次编辑。默认值为 `true`。 + +::: danger 警告 +如果在 `max_expansions` 中指定较大的值,可能会导致性能下降,尤其是当 `prefix_length` 设置为 `0` 时,因为 OpenSearch 需要尝试匹配该单词的大量变体。 +::: + +::: warning 重要 +如果 [`search.allow_expensive_queries`](/query-dsl/#expensive-queries) 设置为 `false`,则不会运行模糊查询。 +::: diff --git a/i18n/zh/query-dsl/term/ids.md b/i18n/zh/query-dsl/term/ids.md new file mode 100644 index 00000000..cd5b2e1c --- /dev/null +++ b/i18n/zh/query-dsl/term/ids.md @@ -0,0 +1,29 @@ +--- +title: IDs +--- + +# IDs 查询 + +使用 `ids` 查询可以在 `_id` 字段中搜索具有一个或多个特定文档 ID 值的文档(Document)。例如,以下查询请求 ID 为 `34229` 和 `91296` 的文档: + +```json +GET shakespeare/_search +{ + "query": { + "ids": { + "values": [ + 34229, + 91296 + ] + } + } +} +``` + +## 参数 + +该查询接受以下参数。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`values` | Array of strings | 要搜索的文档 ID。必需。 diff --git a/i18n/zh/query-dsl/term/index.md b/i18n/zh/query-dsl/term/index.md new file mode 100644 index 00000000..0b372d39 --- /dev/null +++ b/i18n/zh/query-dsl/term/index.md @@ -0,0 +1,28 @@ +--- +title: 词项级查询 +--- + +# 词项级查询 + +词项级查询(Term-level Query)在索引(Index)中搜索包含精确搜索词项的文档(Document)。词项级查询返回的文档不会按相关性评分(Relevance Score)排序。 + +处理文本数据时,词项级查询只应用于映射为 `keyword` 的字段。 + +词项级查询不适合搜索经过分析的文本字段。要返回经过分析的字段,请使用[全文查询](/query-dsl/full-text/)。 + +## 词项级查询类型 + +下表列出了所有词项级查询类型。 + +查询类型 | 描述 +:--- | :--- +[`term`](/query-dsl/term/term) | 在特定字段中搜索包含某个精确词项的文档。 +[`terms`](/query-dsl/term/terms) | 在特定字段中搜索包含一个或多个词项的文档。 +[`terms_set`](/query-dsl/term/terms-set) | 在特定字段中搜索至少匹配指定数量词项的文档。 +[`ids`](/query-dsl/term/ids) | 按文档 ID 搜索文档。 +[`range`](/query-dsl/term/range) | 搜索字段值位于特定范围内的文档。 +[`prefix`](/query-dsl/term/prefix) | 搜索包含以特定前缀开头的词项的文档。 +[`exists`](/query-dsl/term/exists) | 搜索在特定字段中有任意已索引值的文档。 +[`fuzzy`](/query-dsl/term/fuzzy) | 搜索包含与搜索词项相似(在允许的最大 [Levenshtein 距离](https://en.wikipedia.org/wiki/Levenshtein_distance)内)的词项的文档。Levenshtein 距离衡量将一个词项变为另一个词项所需的单字符修改次数。 +[`wildcard`](/query-dsl/term/wildcard) | 搜索包含与通配符模式匹配的词项的文档。 +[`regexp`](/query-dsl/term/regexp) | 搜索包含与正则表达式匹配的词项的文档。 diff --git a/i18n/zh/query-dsl/term/prefix.md b/i18n/zh/query-dsl/term/prefix.md new file mode 100644 index 00000000..801a333d --- /dev/null +++ b/i18n/zh/query-dsl/term/prefix.md @@ -0,0 +1,63 @@ +--- +title: Prefix +--- + +# Prefix 查询 + +使用 `prefix` 查询搜索以特定前缀开头的词项。例如,以下查询搜索 `speaker` 字段中包含以 `KING H` 开头的词项的文档(Document): + +```json +GET shakespeare/_search +{ + "query": { + "prefix": { + "speaker": "KING H" + } + } +} +``` + +要提供参数,可以使用以下扩展语法编写与上述查询等效的查询: + +```json +GET shakespeare/_search +{ + "query": { + "prefix": { + "speaker": { + "value": "KING H" + } + } + } +} +``` + +## 参数 + +该查询接受字段名称(``)作为顶层参数: + +```json +GET _search +{ + "query": { + "prefix": { + "": { + "value": "sample", + ... + } + } + } +} +``` + +`` 接受以下参数。除 `value` 外,所有参数均为可选。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`value` | String | 要在 `` 指定的字段中搜索的词项。 +`case_insensitive` | Boolean | 如果为 `true`,则允许值与已索引的字段值进行不区分大小写的匹配。默认值为 `false`(是否区分大小写由字段的映射决定)。 +`rewrite` | String | 决定 OpenSearch 如何重写多词项查询并为其评分。有效值为 `constant_score`、`scoring_boolean`、`constant_score_boolean`、`top_terms_N`、`top_terms_boost_N` 和 `top_terms_blended_freqs_N`。默认值为 `constant_score`。 + +::: warning 重要 +如果 [`search.allow_expensive_queries`](/query-dsl/#expensive-queries) 设置为 `false`,则不会运行前缀查询。如果启用了 `index_prefixes`,则会忽略 `search.allow_expensive_queries` 设置,并构建和运行经过优化的查询。 +::: diff --git a/i18n/zh/query-dsl/term/range.md b/i18n/zh/query-dsl/term/range.md new file mode 100644 index 00000000..74bfb6f8 --- /dev/null +++ b/i18n/zh/query-dsl/term/range.md @@ -0,0 +1,212 @@ +--- +title: Range +--- + +# Range 查询 + +你可以使用 `range` 查询在字段中搜索某个范围内的值。 + +要搜索 `line_id` 值 >= 10 且 <= 20 的文档(Document),请使用以下请求: + +```json +GET shakespeare/_search +{ + "query": { + "range": { + "line_id": { + "gte": 10, + "lte": 20 + } + } + } +} +``` + +## 运算符 + +range 查询中的字段参数接受以下可选的运算符参数: + +- `gte`:大于或等于 +- `gt`:大于 +- `lte`:小于或等于 +- `lt`:小于 + +## 日期字段 + +你可以对包含日期的字段使用 range 查询。例如,假设你有一个 `products` 索引(Index),并希望查找 2019 年添加的所有产品: + +```json +GET products/_search +{ + "query": { + "range": { + "created": { + "gte": "2019/01/01", + "lte": "2019/12/31" + } + } + } +} +``` + +关于支持的日期格式的更多信息,请参阅[格式](/field-types/supported-field-types/date#formats)。 + +### 格式 + +要在查询中使用与字段映射格式不同的日期格式,请在 `format` 字段中指定该格式。 + +例如,如果 `products` 索引将 `created` 字段映射为 `strict_date_optional_time`,则可以按如下方式为查询日期指定不同的格式: + +```json +GET /products/_search +{ + "query": { + "range": { + "created": { + "gte": "01/01/2022", + "lte": "31/12/2022", + "format":"dd/MM/yyyy" + } + } + } +} +``` + +### 缺失的日期部分 + +OpenSearch 会使用以下值填充缺失的日期部分: + +- `MONTH_OF_YEAR`:`01` +- `DAY_OF_MONTH`:`01` +- `HOUR_OF_DAY`:`23` +- `MINUTE_OF_HOUR`:`59` +- `SECOND_OF_MINUTE`:`59` +- `NANO_OF_SECOND`:`999_999_999` + +如果缺少年份,则不会填充年份。 + +例如,以下请求在开始日期中只指定了年份: + +```json +GET /products/_search +{ + "query": { + "range": { + "created": { + "gte": "2022", + "lte": "2022-12-31" + } + } + } +} +``` + +开始日期会使用默认值填充,因此实际使用的 `gte` 参数为 `2022-01-01T23:59:59.999999999Z`。 + +### 相对日期 + +你可以使用[日期数学表达式](/field-types/supported-field-types/date#date-math)指定相对日期。 + +要从指定日期减去 1 年零 1 天,请使用以下查询: + +```json +GET products/_search +{ + "query": { + "range": { + "created": { + "gte": "2019/01/01||-1y-1d" + } + } + } +} +``` + +在上面的示例中,`2019/01/01` 是日期数学表达式的锚定日期(起点)。在两个竖线字符(`||`)之后,指定相对于锚定日期的数学表达式。在此示例中,减去了 1 年(`-1y`)和 1 天(`-1d`)。 + +你还可以在日期或时间单位后添加正斜杠,对日期进行舍入。 + +要查找过去一年内添加的产品(按月舍入),请使用以下查询: + +```json +GET products/_search +{ + "query": { + "range": { + "created": { + "gte": "now-1y/M" + } + } + } +} +``` + +::: tip 提示 +关键字 `now` 表示当前日期和时间。 +::: + +### 相对日期的舍入 + +下表说明了相对日期的舍入方式。 + +参数 | 舍入规则 | 示例:值 `2022-05-18||/M` 舍入后的结果 +:--- | :--- | :--- +`gt` | 向上舍入到不在舍入区间内的第一毫秒。 | `2022-06-01T00:00:00.000` +`gte` | 向下舍入到第一毫秒。 | `2022-05-01T00:00:00.000` +`lt` | 向下舍入到舍入后日期之前的最后一毫秒。 | `2022-04-30T23:59:59.999` +`lte` | 向上舍入到舍入区间内的最后一毫秒。 | `2022-05-31T23:59:59.999` + +### 时区 + +默认情况下,日期被视为[协调世界时(UTC)](https://en.wikipedia.org/wiki/Coordinated_Universal_Time)。如果在查询中指定了 `time_zone` 参数,则提供的日期值会被转换为 UTC。你可以将 `time_zone` 参数指定为 [UTC 偏移量](https://en.wikipedia.org/wiki/UTC_offset)(例如 `-04:00`),或 [IANA 时区 ID](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones)(例如 `America/New_York`)。例如,以下查询指定查询中提供的 `gte` 日期位于 `-04:00` 时区: + +```json +GET /products/_search +{ + "query": { + "range": { + "created": { + "time_zone": "-04:00", + "gte": "2022-04-17T06:00:00" + } + } + } +} +``` + +上述查询中的 `gte` 参数会被转换为 `2022-04-17T10:00:00 UTC`,即 `2022-04-17T06:00:00-04:00` 对应的 UTC 时间。 + +::: info 注意 +`time_zone` 参数不会影响 `now` 值,因为 `now` 始终对应 UTC 的当前系统时间。 +::: + +## 参数 + +该查询接受字段名称(``)作为顶层参数: + +```json +GET _search +{ + "query": { + "range": { + "": { + "gt": 10, + ... + } + } + } +} +``` + +除了[运算符](#operators)之外,还可以为 `` 指定以下可选参数。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`format` | String | 此查询中日期的[格式](/field-types/supported-field-types/date#formats)。默认值为字段的映射格式。 +`relation` | String | 指示 range 查询如何匹配 [`range`](/field-types/supported-field-types/range) 字段的值。有效值为:
- `INTERSECTS`(默认):匹配 `range` 字段值与查询中提供的范围相交的文档。
- `CONTAINS`:匹配 `range` 字段值包含查询中提供的整个范围的文档。
- `WITHIN`:匹配 `range` 字段值完全位于查询中提供的范围之内的文档。 +`boost` | Floating-point | 按给定的倍数提升查询权重。适用于包含多个查询的搜索。[0, 1) 范围内的值会降低相关性,大于 1 的值会提高相关性。默认值为 `1`。 +`time_zone` | String | 在查询中将 [`date`](/field-types/supported-field-types/date) 值转换为 UTC 时所用的时区。有效值为 ISO 8601 [UTC 偏移量](https://en.wikipedia.org/wiki/List_of_UTC_offsets)和 [IANA 时区 ID](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones)。更多信息,请参阅[时区](#time-zone)。 + +::: warning 重要 +如果 [`search.allow_expensive_queries`](/query-dsl/#expensive-queries) 设置为 `false`,则不会运行针对 [`text`](/field-types/supported-field-types/text) 和 [`keyword`](/field-types/supported-field-types/keyword) 字段的 range 查询。 +::: diff --git a/i18n/zh/query-dsl/term/regexp.md b/i18n/zh/query-dsl/term/regexp.md new file mode 100644 index 00000000..6e2a3a1d --- /dev/null +++ b/i18n/zh/query-dsl/term/regexp.md @@ -0,0 +1,60 @@ +--- +title: Regexp +--- + +# Regexp 查询 + +使用 `regexp` 查询搜索与正则表达式匹配的词项。 + +以下查询搜索以任意大写或小写字母开头、后跟 `amlet` 的词项: + +```json +GET shakespeare/_search +{ + "query": { + "regexp": { + "play_name": "[a-zA-Z]amlet" + } + } +} +``` + +请注意以下重要事项: + +- 正则表达式作用于字段中的词项(即词元(Token)),而不是整个字段。 +- 默认情况下,正则表达式的最大长度为 1,000 个字符。要更改最大长度,请更新 `index.max_regex_length` 设置。 +- 正则表达式使用 Lucene 语法,该语法与更标准化的实现有所不同。请充分测试,以确保得到预期的结果。更多信息,请参阅 [Lucene 文档](https://lucene.apache.org/core/8_9_0/core/index.html)。 +- 为了提高 regexp 查询的性能,请避免使用没有前缀或后缀的通配符模式,例如 `.*` 或 `.*?+`。 +- `regexp` 查询可能是开销较大的操作,需要将 [`search.allow_expensive_queries`](/query-dsl/#expensive-queries) 设置为 `true`。在频繁执行 `regexp` 查询之前,请测试其对集群性能的影响,并考虑能够获得类似结果的替代查询。 + +## 参数 + +该查询接受字段名称(``)作为顶层参数: + +```json +GET _search +{ + "query": { + "regexp": { + "": { + "value": "[Ss]ample", + ... + } + } + } +} +``` + +`` 接受以下参数。除 `value` 外,所有参数均为可选。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`value` | String | 用于匹配 `` 指定字段中词项的正则表达式。 +`case_insensitive` | Boolean | 如果为 `true`,则允许正则表达式值与已索引的字段值进行不区分大小写的匹配。默认值为 `false`(是否区分大小写由字段的映射决定)。 +`flags` | String | 为 Lucene 正则表达式引擎启用可选运算符。 +`max_determinized_states` | Integer | Lucene 会将正则表达式转换为具有若干确定化状态的自动机。该参数指定查询所需的最大自动机状态数,用于防止资源消耗过高。要运行复杂的正则表达式,可能需要增大该参数的值。默认值为 10,000。 +`rewrite` | String | 决定 OpenSearch 如何重写多词项查询并为其评分。有效值为 `constant_score`、`scoring_boolean`、`constant_score_boolean`、`top_terms_N`、`top_terms_boost_N` 和 `top_terms_blended_freqs_N`。默认值为 `constant_score`。 + +::: warning 重要 +如果 [`search.allow_expensive_queries`](/query-dsl/#expensive-queries) 设置为 `false`,则不会运行 `regexp` 查询。 +::: diff --git a/i18n/zh/query-dsl/term/term.md b/i18n/zh/query-dsl/term/term.md new file mode 100644 index 00000000..a11fddcd --- /dev/null +++ b/i18n/zh/query-dsl/term/term.md @@ -0,0 +1,92 @@ +--- +title: Term +--- + +# Term 查询 + +使用 `term` 查询在字段中搜索精确的词项。例如,以下查询搜索具有精确行号的行: + +```json +GET shakespeare/_search +{ + "query": { + "term": { + "line_id": { + "value": "61809" + } + } + } +} +``` + +在为文档(Document)建立索引时,`text` 字段会被[分析](/analyzers/)。分析过程包括对文本进行分词、转换为小写以及去除标点符号。`match` 查询会分析查询文本,而 `term` 查询只匹配精确的词项,因此可能无法返回相关的结果。请避免在 `text` 字段上使用 `term` 查询。更多信息,请参阅[词项级查询与全文查询的比较](/query-dsl/term-vs-full-text)。 + +你可以在 `case_insensitive` 参数中指定查询不区分大小写: + +```json +GET shakespeare/_search +{ + "query": { + "term": { + "speaker": { + "value": "HAMLET", + "case_insensitive": true + } + } + } +} +``` + +响应中包含匹配的文档,而不考虑大小写差异: + +```json +"hits": { + "total": { + "value": 1582, + "relation": "eq" + }, + "max_score": 2, + "hits": [ + { + "_index": "shakespeare", + "_id": "32700", + "_score": 2, + "_source": { + "type": "line", + "line_id": 32701, + "play_name": "Hamlet", + "speech_number": 9, + "line_number": "1.2.66", + "speaker": "HAMLET", + "text_entry": "[Aside] A little more than kin, and less than kind." + } + }, + ... +} +``` + +## 参数 + +该查询接受字段名称(``)作为顶层参数: + +```json +GET _search +{ + "query": { + "term": { + "": { + "value": "sample", + ... + } + } + } +} +``` + +`` 接受以下参数。除 `value` 外,所有参数均为可选。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`value` | String | 要在 `` 指定的字段中搜索的词项。只有当文档的字段值与该词项完全匹配(包括空格和大小写)时,才会在结果中返回该文档。 +`boost` | Floating-point | 按给定的倍数提升查询权重。适用于包含多个查询的搜索。[0, 1) 范围内的值会降低相关性,大于 1 的值会提高相关性。默认值为 `1`。 +`case_insensitive` | Boolean | 如果为 `true`,则允许值与已索引的字段值进行不区分大小写的匹配。默认值为 `false`(是否区分大小写由字段的映射决定)。 diff --git a/i18n/zh/query-dsl/term/terms-set.md b/i18n/zh/query-dsl/term/terms-set.md new file mode 100644 index 00000000..0af1693c --- /dev/null +++ b/i18n/zh/query-dsl/term/terms-set.md @@ -0,0 +1,160 @@ +--- +title: Terms set +--- + +# Terms set 查询 + +使用 terms set 查询,可以搜索在指定字段中至少匹配指定数量精确词项的文档(Document)。`terms_set` 查询与 `terms` 查询类似,区别在于你可以指定返回文档所需的最少匹配词项数。你可以通过索引(Index)中的某个字段或通过脚本来指定这个数量。 + +例如,假设一个索引包含学生姓名以及这些学生选修的课程。在为该索引设置映射(Mapping)时,需要提供一个[数值](/field-types/supported-field-types/numeric)字段,用于指定返回文档所需的最少匹配词项数: + +```json +PUT students +{ + "mappings": { + "properties": { + "name": { + "type": "keyword" + }, + "classes": { + "type": "keyword" + }, + "min_required": { + "type": "integer" + } + } + } +} +``` + +接下来,索引两个与学生对应的文档: + +```json +PUT students/_doc/1 +{ + "name": "Mary Major", + "classes": [ "CS101", "CS102", "MATH101" ], + "min_required": 2 +} +``` + +```json +PUT students/_doc/2 +{ + "name": "John Doe", + "classes": [ "CS101", "MATH101", "ENG101" ], + "min_required": 2 +} +``` + +现在搜索至少选修了以下课程中两门的学生:`CS101`、`CS102`、`MATH101`: + +```json +GET students/_search +{ + "query": { + "terms_set": { + "classes": { + "terms": [ "CS101", "CS102", "MATH101" ], + "minimum_should_match_field": "min_required" + } + } + } +} +``` + +响应中包含这两个文档: + +```json +{ + "took" : 44, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 2, + "relation" : "eq" + }, + "max_score" : 1.4544616, + "hits" : [ + { + "_index" : "students", + "_id" : "1", + "_score" : 1.4544616, + "_source" : { + "name" : "Mary Major", + "classes" : [ + "CS101", + "CS102", + "MATH101" + ], + "min_required" : 2 + } + }, + { + "_index" : "students", + "_id" : "2", + "_score" : 0.5013843, + "_source" : { + "name" : "John Doe", + "classes" : [ + "CS101", + "MATH101", + "ENG101" + ], + "min_required" : 2 + } + } + ] + } +} +``` + +要通过脚本指定文档应匹配的最少词项数,请在 `minimum_should_match_script` 字段中提供脚本: + +```json +GET students/_search +{ + "query": { + "terms_set": { + "classes": { + "terms": [ "CS101", "CS102", "MATH101" ], + "minimum_should_match_script": { + "source": "Math.min(params.num_terms, doc['min_required'].value)" + } + } + } + } +} +``` + +## 参数 + +该查询接受字段名称(``)作为顶层参数: + +```json +GET _search +{ + "query": { + "terms_set": { + "": { + "terms": [ "term1", "term2" ], + ... + } + } + } +} +``` + +`` 接受以下参数。除 `terms` 外,所有参数均为可选。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`terms` | Array of strings | 要在 `` 指定的字段中搜索的词项数组。只有当所需数量的词项与文档的字段值完全匹配(包括空格和大小写)时,才会在结果中返回该文档。 +`minimum_should_match_field` | String | [数值](/field-types/supported-field-types/numeric)字段的名称,该字段指定在结果中返回文档所需的匹配词项数。 +`minimum_should_match_script` | String | 返回在结果中返回文档所需匹配词项数的脚本。 diff --git a/i18n/zh/query-dsl/term/terms.md b/i18n/zh/query-dsl/term/terms.md new file mode 100644 index 00000000..3484d0ac --- /dev/null +++ b/i18n/zh/query-dsl/term/terms.md @@ -0,0 +1,240 @@ +--- +title: Terms +--- + +# Terms 查询 + +使用 `terms` 查询在同一字段中搜索多个词项。例如,以下查询搜索 ID 为 `61809` 和 `61810` 的行: + +```json +GET shakespeare/_search +{ + "query": { + "terms": { + "line_id": [ + "61809", + "61810" + ] + } + } +} +``` + +只要文档(Document)与数组中的任一词项匹配,就会返回该文档。 + +默认情况下,`terms` 查询中允许的最大词项数为 65,536。要更改最大词项数,请更新 `index.max_terms_count` 设置。 + +::: info 注意 +能否[高亮显示](/search-plugins/searching-data/highlight) terms 查询的结果无法保证,这取决于高亮器类型和查询中的词项数量。 +::: + +## 参数 + +该查询接受以下参数。所有参数均为可选。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`` | String | 要搜索的字段。只有当文档的字段值与至少一个词项完全匹配(包括空格和大小写)时,才会在结果中返回该文档。 +`boost` | Floating-point | 按给定的倍数提升查询权重。适用于包含多个查询的搜索。[0, 1) 范围内的值会降低相关性,大于 1 的值会提高相关性。默认值为 `1`。 + +## 词项查找 + +词项查找(Terms Lookup)会获取单个文档的字段值,并将其用作搜索词项。你可以使用词项查找来搜索大量词项。 + +要使用词项查找,必须启用 `_source` 映射字段,因为词项查找会从文档中获取值。`_source` 字段默认是启用的。 + +词项查找会尝试从本地数据节点上的分片(Shard)获取文档字段值。因此,使用只有一个主分片、且在所有相关数据节点上都有完整副本的索引(Index),可以减少网络流量。 + +### 示例 + +例如,创建一个包含学生数据的索引,并将 `student_id` 映射为 `keyword`: + +```json +PUT students +{ + "mappings": { + "properties": { + "student_id": { "type": "keyword" } + } + } +} +``` + +接下来,索引三个与学生对应的文档: + +```json +PUT students/_doc/1 +{ + "name": "Jane Doe", + "student_id" : "111" +} +``` + +```json +PUT students/_doc/2 +{ + "name": "Mary Major", + "student_id" : "222" +} +``` + +```json +PUT students/_doc/3 +{ + "name": "John Doe", + "student_id" : "333" +} +``` + +再创建一个包含课程信息的独立索引,其中包括课程名称以及由选修该课程的学生 ID 组成的数组: + +```json +PUT classes/_doc/101 +{ + "name": "CS101", + "enrolled" : ["111" , "222"] +} +``` + +要搜索选修了 `CS101` 课程的学生,请指定该课程对应文档的文档 ID、该文档所在的索引,以及词项所在字段的路径: + +```json +GET students/_search +{ + "query": { + "terms": { + "student_id": { + "index": "classes", + "id": "101", + "path": "enrolled" + } + } + } +} +``` + +响应中包含 `students` 索引中 ID 与 `enrolled` 数组中某个值匹配的每个学生的文档: + +```json +{ + "took": 13, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "students", + "_id": "1", + "_score": 1, + "_source": { + "name": "Jane Doe", + "student_id": "111" + } + }, + { + "_index": "students", + "_id": "2", + "_score": 1, + "_source": { + "name": "Mary Major", + "student_id": "222" + } + } + ] + } +} +``` + +### 示例:嵌套字段 + +第二个示例演示如何查询嵌套字段。假设一个索引包含以下文档: + +```json +PUT classes/_doc/102 +{ + "name": "CS102", + "enrolled_students" : { + "id_list" : ["111" , "333"] + } +} +``` + +要搜索选修了 `CS102` 的学生,请在 `path` 参数中使用点路径表示法指定字段的完整路径: + +```json +ET students/_search +{ + "query": { + "terms": { + "student_id": { + "index": "classes", + "id": "102", + "path": "enrolled_students.id_list" + } + } + } +} +``` + +响应中包含匹配的文档: + +```json +{ + "took": 18, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "students", + "_id": "1", + "_score": 1, + "_source": { + "name": "Jane Doe", + "student_id": "111" + } + }, + { + "_index": "students", + "_id": "3", + "_score": 1, + "_source": { + "name": "John Doe", + "student_id": "333" + } + } + ] + } +} +``` + +### 参数 {#parameters-1} + +下表列出了词项查找的参数。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`index` | String | 要从中获取字段值的索引名称。必需。 +`id` | String | 要从中获取字段值的文档的文档 ID。必需。 +`path` | String | 要从中获取字段值的字段名称。使用点路径表示法指定嵌套字段。必需。 +`routing` | String | 要从中获取字段值的文档的自定义路由值。可选。如果在索引文档时提供了自定义路由值,则为必需。 diff --git a/i18n/zh/query-dsl/term/wildcard.md b/i18n/zh/query-dsl/term/wildcard.md new file mode 100644 index 00000000..0750b3e7 --- /dev/null +++ b/i18n/zh/query-dsl/term/wildcard.md @@ -0,0 +1,64 @@ +--- +title: Wildcard +--- + +# Wildcard 查询 + +使用通配符查询(Wildcard Query)搜索与通配符模式匹配的词项。通配符查询支持以下运算符。 + +运算符 | 描述 +:--- | :--- +`*` | 匹配零个或多个字符。 +`?` | 匹配任意单个字符。 +`case_insensitive` | 如果为 `true`,则通配符查询不区分大小写。如果为 `false`,则通配符查询区分大小写。默认值为 `false`(区分大小写)。 + +要以区分大小写的方式搜索以 `H` 开头、以 `Y` 结尾的词项,请使用以下请求: + +```json +GET shakespeare/_search +{ + "query": { + "wildcard": { + "speaker": { + "value": "H*Y", + "case_insensitive": false + } + } + } +} +``` + +如果将 `*` 改为 `?`,则不会得到任何匹配结果,因为 `?` 只代表单个字符。 + +通配符查询往往较慢,因为它们需要遍历大量词项。请避免将通配符放在查询的开头,因为这在资源和时间上都可能是开销非常大的操作。 + +## 参数 + +该查询接受字段名称(``)作为顶层参数: + +```json +GET _search +{ + "query": { + "wildcard": { + "": { + "value": "patt*rn", + ... + } + } + } +} +``` + +`` 接受以下参数。除 `value` 外,所有参数均为可选。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`value` | String | 用于匹配 `` 指定字段中词项的通配符模式。 +`boost` | Floating-point | 按给定的倍数提升查询权重。适用于包含多个查询的搜索。[0, 1) 范围内的值会降低相关性,大于 1 的值会提高相关性。默认值为 `1`。 +`case_insensitive` | Boolean | 如果为 `true`,则允许值与已索引的字段值进行不区分大小写的匹配。默认值为 `false`(是否区分大小写由字段的映射决定)。 +`rewrite` | String | 决定 OpenSearch 如何重写多词项查询并为其评分。有效值为 `constant_score`、`scoring_boolean`、`constant_score_boolean`、`top_terms_N`、`top_terms_boost_N` 和 `top_terms_blended_freqs_N`。默认值为 `constant_score`。 + +::: warning 重要 +如果 [`search.allow_expensive_queries`](/query-dsl/#expensive-queries) 设置为 `false`,则不会运行通配符查询。 +::: diff --git a/i18n/zh/search-plugins/async/index.md b/i18n/zh/search-plugins/async/index.md new file mode 100644 index 00000000..c5e4b059 --- /dev/null +++ b/i18n/zh/search-plugins/async/index.md @@ -0,0 +1,254 @@ +--- +title: 异步搜索 +--- + +# 异步搜索 + +搜索大量数据可能需要很长时间,尤其是在跨温节点(warm node)或多个远程集群进行搜索时。 + +OpenSearch 中的异步搜索(Asynchronous Search)允许你发送在后台运行的搜索请求。你可以监控这些搜索的进度,并在部分结果可用时获取它们。搜索完成后,你可以保存结果,以便稍后查看。 + +## REST API + + +要执行异步搜索,请向 `_plugins/_asynchronous_search` 发送请求,并在请求体中包含查询: + +```json +POST _plugins/_asynchronous_search +``` + +你可以指定以下选项。 + +选项 | 描述 | 默认值 | 必需 +:--- | :--- |:--- |:--- | +`wait_for_completion_timeout` | 你计划等待结果的时间。在这段时间内得到的结果都可以像普通搜索一样查看。剩余结果可以根据 ID 轮询获取。最大值为 300 秒。 | 1 秒 | 否 +`keep_on_completion` | 搜索完成后是否将结果保存在集群中。你可以稍后查看已保存的结果。 | `false` | 否 +`keep_alive` | 结果在集群中保存的时长。例如,`2d` 表示结果在集群中保存 48 小时。超过该时长或搜索被取消后,已保存的搜索结果会被删除。注意,该时长包含查询执行时间。如果查询运行超过该时长,进程会自动取消该查询。 | 12 小时 | 否 + +#### 示例请求 + +```json +POST _plugins/_asynchronous_search/?pretty&size=10&wait_for_completion_timeout=1ms&keep_on_completion=true&request_cache=false +{ + "aggs": { + "city": { + "terms": { + "field": "city", + "size": 10 + } + } + } +} +``` + +#### 示例响应 + +```json +{ + "*id*": "FklfVlU4eFdIUTh1Q1hyM3ZnT19fUVEUd29KLWZYUUI3TzRpdU5wMjRYOHgAAAAAAAAABg==", + "state": "RUNNING", + "start_time_in_millis": 1599833301297, + "expiration_time_in_millis": 1600265301297, + "response": { + "took": 15, + "timed_out": false, + "terminated_early": false, + "num_reduce_phases": 4, + "_shards": { + "total": 21, + "successful": 4, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 807, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "city": { + "doc_count_error_upper_bound": 16, + "sum_other_doc_count": 403, + "buckets": [ + { + "key": "downsville", + "doc_count": 1 + }, + .... + .... + .... + { + "key": "blairstown", + "doc_count": 1 + } + ] + } + } + } +} +``` + +#### 响应参数 + +选项 | 描述 +:--- | :--- +`id` | 异步搜索的 ID。使用该 ID 可以监控搜索进度、获取部分结果和/或删除结果。如果异步搜索在超时时间内完成,响应中不包含该 ID,因为结果不会存储在集群中。 +`state` | 表示搜索仍在运行还是已经完成,以及结果是否持久化在集群中。可能的状态有 `RUNNING`、`SUCCEEDED`、`FAILED`、`PERSISTING`、`PERSIST_SUCCEEDED`、`PERSIST_FAILED`、`CLOSED` 和 `STORE_RESIDENT`。 +`start_time_in_millis` | 开始时间,单位为毫秒。 +`expiration_time_in_millis` | 过期时间,单位为毫秒。 +`took` | 搜索运行的总时间。 +`response` | 实际的搜索响应。 +`num_reduce_phases` | 协调节点汇总一批批分片响应结果的次数(默认为 5)。如果该数字比上次获取结果时有所增加,说明搜索响应中会包含更多结果。 +`total` | 运行该搜索的分片总数。 +`successful` | 协调节点成功接收的分片响应数。 +`aggregations` | 到目前为止各分片已完成的部分聚合结果。 + +## 获取部分结果 + + +提交异步搜索请求后,你可以使用异步搜索响应中的 ID 请求部分响应。 + +```json +GET _plugins/_asynchronous_search/?pretty +``` + +#### 示例响应 {#example-response-1} + +```json +{ + "id": "Fk9lQk5aWHJIUUltR2xGWnpVcWtFdVEURUN1SWZYUUJBVkFVMEJCTUlZUUoAAAAAAAAAAg==", + "state": "STORE_RESIDENT", + "start_time_in_millis": 1599833907465, + "expiration_time_in_millis": 1600265907465, + "response": { + "took": 83, + "timed_out": false, + "_shards": { + "total": 20, + "successful": 20, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1000, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "bank", + "_id": "1", + "_score": 1, + "_source": { + "email": "amberduke@abc.com", + "city": "Brogan", + "state": "IL" + } + }, + {....} + ] + }, + "aggregations": { + "city": { + "doc_count_error_upper_bound": 0, + "sum_other_doc_count": 997, + "buckets": [ + { + "key": "belvoir", + "doc_count": 2 + }, + { + "key": "aberdeen", + "doc_count": 1 + }, + { + "key": "abiquiu", + "doc_count": 1 + } + ] + } + } + } +} +``` + +响应成功持久化后,响应中会返回 `STORE_RESIDENT` 状态。 + +你可以结合 `wait_for_completion_timeout` 参数轮询该 ID,在指定的时间内等待接收结果。 + +对于 `keep_on_completion` 为 `true` 且 `keep_alive` 时间足够长的异步搜索,你可以一直轮询这些 ID,直到搜索完成。如果不想定期轮询每个 ID,可以通过 `keep_alive` 参数将结果保留在集群中,稍后再来查看。 + +## 删除搜索和结果 + + +要删除异步搜索: + +``` +DELETE _plugins/_asynchronous_search/?pretty +``` + +- 如果搜索仍在运行,OpenSearch 会取消该搜索。 +- 如果搜索已完成,OpenSearch 会删除已保存的结果。 + +#### 示例响应 {#example-response-2} + +```json +{ + "acknowledged": "true" +} +``` + +## 监控统计信息 + + +你可以使用 stats API 操作来监控正在运行、已完成和/或已持久化的异步搜索。 + +```json +GET _plugins/_asynchronous_search/stats +``` + +#### 示例响应 {#example-response-3} + +```json +{ + "_nodes": { + "total": 8, + "successful": 8, + "failed": 0 + }, + "cluster_name": "264071961897:asynchronous-search", + "nodes": { + "JKEFl6pdRC-xNkKQauy7Yg": { + "asynchronous_search_stats": { + "submitted": 18236, + "initialized": 112, + "search_failed": 56, + "search_completed": 56, + "rejected": 18124, + "persist_failed": 0, + "cancelled": 1, + "running_current": 399, + "persisted": 100 + } + } + } +} +``` + +#### 响应参数 {#response-parameters-1} + +选项 | 描述 +:--- | :--- +`submitted` | 已提交的异步搜索请求数。 +`initialized` | 已初始化的异步搜索请求数。 +`rejected` | 被拒绝的异步搜索请求数。 +`search_completed` | 已完成且响应成功的异步搜索请求数。 +`search_failed` | 已完成但响应失败的异步搜索请求数。 +`persisted` | 最终结果已成功持久化到集群中的异步搜索请求数。 +`persist_failed` | 最终结果未能持久化到集群中的异步搜索请求数。 +`running_current` | 在给定协调节点上正在运行的异步搜索请求数。 +`cancelled` | 在搜索运行期间被取消的异步搜索请求数。 diff --git a/i18n/zh/search-plugins/async/security.md b/i18n/zh/search-plugins/async/security.md new file mode 100644 index 00000000..2b5b3540 --- /dev/null +++ b/i18n/zh/search-plugins/async/security.md @@ -0,0 +1,135 @@ +--- +title: 异步搜索安全 +--- + +# 异步搜索安全 + +你可以将安全插件(Security plugin)与异步搜索结合使用,限制非管理员用户只能执行特定操作。例如,你可能希望某些用户只能提交或删除异步搜索,而另一些用户只能查看结果。 + +所有异步搜索索引都作为系统索引受到保护。只有超级管理员用户,或持有传输层安全(Transport Layer Security,TLS)证书的管理员用户才能访问系统索引。有关更多信息,请参阅[系统索引](/security/configuration/system-indices)。 + +## 基本权限 + +作为管理员用户,你可以使用安全插件根据用户需要访问的 API 操作为其分配特定权限。有关支持的 API 操作列表,请参阅[异步搜索](/)。 + +安全插件有两个内置角色,可覆盖大多数异步搜索使用场景:`asynchronous_search_full_access` 和 `asynchronous_search_read_access`。有关各角色的说明,请参阅[预定义角色](/security/access-control/users-roles#predefined-roles)。 + +如果这些角色不能满足你的需求,可以根据使用场景自由组合单独的异步搜索权限。每个操作都对应 REST API 中的一个操作。例如,`cluster:admin/opensearch/asynchronous_search/delete` 权限允许你删除之前提交的异步搜索。 + +### 关于异步搜索与细粒度访问控制的说明 + +按照设计,异步搜索插件会从目标索引中提取数据,并将数据存储在单独的索引中,以便具有相应权限的用户获取搜索结果。虽然拥有 `asynchronous_search_read_access` 或 `cluster:admin/opensearch/asynchronous_search/get` 权限的用户本身无法提交异步搜索请求,但该用户可以使用相关的搜索 ID 获取并查看搜索结果。[文档级安全](/security/access-control/document-level-security)(DLS)和[字段级安全](/security/access-control/field-level-security)(FLS)访问控制旨在保护目标索引中的数据。但一旦数据存储到该索引之外,拥有这些访问权限的用户就能使用搜索 ID 获取并查看异步搜索结果,其中可能包含目标索引中原本被 DLS 和 FLS 访问控制隐藏的数据。 + +为了降低非预期用户查看到可能描述某个索引的搜索结果的可能性,我们建议管理员启用基于角色的访问控制,并在为目标用户组分配权限时牢记这类设计因素。有关详细信息,请参阅[按后端角色限制访问](#advanced-limit-access-by-backend-role)。 + +## (高级)按后端角色限制访问 + +使用后端角色(backend role)可以基于角色对异步搜索配置细粒度访问。例如,组织中不同部门的用户只能查看本部门拥有的异步搜索。 + +首先,确保你的用户拥有相应的[后端角色](/security/access-control/)。后端角色通常来自 [LDAP 服务器](/security/authentication-backends/ldap)或 [SAML 提供商](/security/authentication-backends/saml)。不过,如果你使用内部用户数据库,可以使用 REST API [手动添加](/security/access-control/api#create-user)。 + +现在,当用户在 OpenSearch Dashboards 中查看异步搜索资源(或调用 REST API)时,只能看到由拥有其后端角色子集的用户提交的异步搜索。 +例如,假设有两个用户:`judy` 和 `elon`。 + +`judy` 拥有 IT 后端角色: + +```json +PUT _plugins/_security/api/internalusers/judy +{ + "password": "judy", + "backend_roles": [ + "IT" + ], + "attributes": {} +} +``` + +`elon` 拥有 admin 后端角色: + +```json +PUT _plugins/_security/api/internalusers/elon +{ + "password": "elon", + "backend_roles": [ + "admin" + ], + "attributes": {} +} +``` + +`judy` 和 `elon` 都拥有异步搜索的完全访问权限: + +```json +PUT _plugins/_security/api/rolesmapping/async_full_access +{ + "backend_roles": [], + "hosts": [], + "users": [ + "judy", + "elon" + ] +} +``` + +由于他们的后端角色不同,`judy` 提交的异步搜索对 `elon` 不可见,反之亦然。 + +`judy` 至少需要拥有 `elon` 所有角色的超集,才能看到 `elon` 的异步搜索。 + +例如,如果 `judy` 拥有五个后端角色,而 `elon` 拥有其中一个角色,那么 `judy` 可以看到 `elon` 提交的异步搜索,但 `elon` 看不到 `judy` 提交的异步搜索。也就是说,`judy` 可以对 `elon` 提交的异步搜索执行 GET 和 DELETE 操作,反之则不行。 + +如果所有用户都没有任何后端角色,那么这三个用户都能看到彼此的搜索。 + +例如,假设有三个用户:`judy`、`elon` 和 `jack`。 + +`judy`、`elon` 和 `jack` 都没有设置后端角色: + +```json +PUT _plugins/_security/api/internalusers/judy +{ + "password": "judy", + "backend_roles": [], + "attributes": {} +} +``` + +```json +PUT _plugins/_security/api/internalusers/elon +{ + "password": "elon", + "backend_roles": [], + "attributes": {} +} +``` + +```json +PUT _plugins/_security/api/internalusers/jack +{ + "password": "jack", + "backend_roles": [], + "attributes": {} +} +``` + +`judy` 和 `elon` 都拥有异步搜索的完全访问权限: + +```json +PUT _plugins/_security/api/rolesmapping/async_full_access +{ + "backend_roles": [], + "hosts": [], + "users": ["judy","elon"] +} +``` + +`jack` 拥有异步搜索结果的读取权限: + +```json +PUT _plugins/_security/api/rolesmapping/async_read_access +{ + "backend_roles": [], + "hosts": [], + "users": ["jack"] +} +``` + +由于所有用户都没有后端角色,他们能够看到彼此的异步搜索。因此,如果 `judy` 提交了一个异步搜索,拥有完全访问权限的 `elon` 能够看到该搜索。拥有读取权限的 `jack` 也能看到 `judy` 的异步搜索。 diff --git a/i18n/zh/search-plugins/async/settings.md b/i18n/zh/search-plugins/async/settings.md new file mode 100644 index 00000000..17e84509 --- /dev/null +++ b/i18n/zh/search-plugins/async/settings.md @@ -0,0 +1,28 @@ +--- +title: 设置 +--- + +# 异步搜索设置 + +异步搜索插件在标准 OpenSearch 集群设置的基础上添加了若干设置。这些设置是动态的,因此无需重启集群即可更改插件的默认行为。要了解有关静态和动态设置的更多信息,请参阅[配置 OpenSearch](/install-and-configure/configuring-opensearch/)。 + +你可以将这些设置标记为 `persistent` 或 `transient`。 + +例如,要更新结果索引的保留期限: + +```json +PUT _cluster/settings +{ + "transient": { + "plugins.asynchronous_search.max_wait_for_completion_timeout": "5m" + } +} +``` + +设置 | 默认值 | 描述 +:--- | :--- | :--- +`plugins.asynchronous_search.max_search_running_time` | 12 小时 | 搜索的最长运行时间,超过该时间搜索将被终止。 +`plugins.asynchronous_search.node_concurrent_running_searches` | 20 | 每个协调节点上并发运行的搜索数。 +`plugins.asynchronous_search.max_keep_alive` | 5 天 | 搜索结果在集群中可以存储的最长时间。 +`plugins.asynchronous_search.max_wait_for_completion_timeout` | 1 分钟 | `wait_for_completion_timeout` 参数的最大值。 +`plugins.asynchronous_search.persist_search_failures` | false | 将以搜索失败结束的异步搜索结果持久化到系统索引中。 diff --git a/i18n/zh/search-plugins/concurrent-segment-search.md b/i18n/zh/search-plugins/concurrent-segment-search.md new file mode 100644 index 00000000..2a899ad8 --- /dev/null +++ b/i18n/zh/search-plugins/concurrent-segment-search.md @@ -0,0 +1,106 @@ +--- +title: 并发段搜索 +--- + +# 并发段搜索 + +使用并发段搜索(concurrent segment search)可以在查询阶段并行搜索各个段(segment)。在以下情况下,并发段搜索可以降低搜索延迟: + +- 发送长时间运行的请求时,例如包含聚合或大范围查询的请求 +- 作为将段强制合并为单个段以提升性能的替代方案 + +## 背景 + +在 OpenSearch 中,每个搜索请求都遵循分散-汇聚(scatter-gather)协议。协调节点接收搜索请求,判断需要哪些分片(shard)来处理该请求,并向每个分片发送分片级搜索请求。每个收到请求的分片使用 Lucene 在本地执行该请求并返回结果。协调节点合并从所有分片收到的响应,并将搜索响应发送回客户端。如果客户端在响应中请求了某些文档字段或整个文档,协调节点还可以在将最终结果返回客户端之前执行获取(fetch)阶段,这一步是可选的。 + +## 并发搜索段 + +如果不使用并发段搜索,Lucene 会在查询阶段按顺序在每个分片的所有段上执行请求,然后由查询阶段收集该搜索请求的排名靠前的命中(hit)。使用并发段搜索时,每个分片级请求会在查询阶段并行搜索各个段。对于每个分片,段会被划分为多个*切片*(slice)。每个切片都是可以在单独线程上并行执行的工作单元,因此切片数量决定了分片级请求的最大并行度。所有切片完成工作后,Lucene 会对这些切片执行归约(reduce)操作,将它们合并并生成该分片级请求的最终结果。切片使用新的 `index_searcher` 线程池执行,该线程池不同于处理分片级请求的 `search` 线程池。 + +## 在索引或集群级别启用并发段搜索 + +默认情况下,集群上的并发段搜索处于禁用状态。你可以在两个级别启用并发段搜索: + +- 集群级别 +- 索引级别 + +::: info 注意 +索引级设置的优先级高于集群级设置。因此,如果启用了集群设置但禁用了索引设置,则该索引的并发段搜索将被禁用。 +::: + +要为集群中的所有索引启用并发段搜索,请设置以下动态集群设置: + +```json +PUT _cluster/settings +{ + "persistent":{ + "search.concurrent_segment_search.enabled": true + } +} +``` + +要为特定索引启用并发段搜索,请在端点中指定索引名称: + +```json +PUT /_settings +{ + "index.search.concurrent_segment_search.enabled": true +} +``` + +## 切片机制 + +你可以从两种可用机制中选择一种,用于将段分配给切片:默认的 [Lucene 机制](#the-lucene-mechanism)或[最大切片数机制](#the-max-slice-count-mechanism)。 + +### Lucene 机制 + +默认情况下,Lucene 为分片中的每个切片最多分配 25 万个文档或 5 个段(以先达到者为准)。例如,假设某个分片有 11 个段,前 5 个段各有 25 万个文档,后 6 个段各有 2 万个文档。前 5 个段将各自分配到 1 个切片,因为每个段都已包含单个切片允许的最大文档数。接下来的 5 个段将全部分配到另一个切片,因为达到了单个切片允许的最大段数。第 11 个切片将被分配到一个单独的切片中。 + +### 最大切片数机制 + +*最大切片数*(max slice count)机制是另一种切片机制,它使用静态配置的最大切片数,并以轮询(round-robin)方式在各切片之间分配段。当顶层分片请求已经过多,而你希望限制每个请求的切片数以减少切片之间的竞争时,这种机制非常有用。 + +### 设置切片机制 + +默认情况下,并发段搜索使用 Lucene 机制计算每个分片级请求的切片数。如果要改用最大切片数机制,请在 `opensearch.yml` 配置文件中配置 `search.concurrent.max_slice_count` 静态设置: + +```yaml +search.concurrent.max_slice_count: 2 +``` + +`search.concurrent.max_slice_count` 设置可以取以下有效值: +- `0`:使用默认的 Lucene 机制。 +- 正整数:使用最大目标切片数机制。通常,2 到 8 之间的值就足够了。 + +## 限制 + +以下聚合不支持并发搜索模型。如果搜索请求包含其中任一聚合,即使在集群级别或索引级别启用了并发段搜索,该请求也会通过非并发路径执行。 +- [join](/field-types/supported-field-types/join) 字段上的父聚合。有关更多信息,请参阅[此 GitHub issue](https://github.com/opensearch-project/OpenSearch/issues/9316)。 +- `sampler` 和 `diversified_sampler` 聚合。有关更多信息,请参阅[此 GitHub issue](https://github.com/opensearch-project/OpenSearch/issues/11075)。 +- 组合(composite)聚合。有关更多信息,请参阅[此 GitHub issue](https://github.com/opensearch-project/OpenSearch/issues/12331)。 + +## 其他注意事项 + +以下各节介绍并发段搜索的其他注意事项。 + +### `terminate_after` 搜索参数 {#the-terminateafter-search-parameter} + +[`terminate_after` 搜索参数](/api-reference/search#url-parameters)用于在收集到指定数量的文档后终止搜索请求。如果在请求中包含 `terminate_after` 参数,并发段搜索将被禁用,请求将以非并发方式运行。 + +通常,查询会使用较小的 `terminate_after` 值,由于搜索是在缩小后的数据集上执行的,因此会很快完成。所以在这种情况下,并发搜索可能无法进一步提升性能。此外,当 `terminate_after` 与其他搜索请求参数(例如 `track_total_hits` 或 `size`)一起使用时,会增加复杂性并改变预期的查询行为。对包含 `terminate_after` 的搜索请求回退到非并发路径,可以确保并发请求与非并发请求的结果一致。 + +### 排序 + +根据段的数据布局,排序优化功能可以基于最小值和最大值以及之前收集的值裁剪掉整个段。如果排名靠前的值出现在前几个段中,而其他所有段都被裁剪掉,那么在使用并发段搜索进行排序时,查询延迟可能会增加。相反,如果排名靠前的值位于最后几个段中,那么使用并发段搜索可能会降低延迟。 + +### Terms 聚合 + +非并发搜索会计算文档计数误差,并在 `doc_count_error_upper_bound` 响应参数中返回该值。在并发段搜索期间,`shard_size` 参数在段切片级别生效。因此,并发搜索可能会引入额外的文档计数误差。 + +有关 `shard_size` 如何影响 `doc_count_error_upper_bound` 和所收集的桶的更多信息,请参阅[此 GitHub issue](https://github.com/opensearch-project/OpenSearch/issues/11680#issuecomment-1885882985)。 + +## 开发者信息:AggregatorFactory 的变更 + +由于实现细节的原因,并非所有聚合器类型都支持并发段搜索。为此,我们在 `AggregatorFactory` 类中引入了 [`supportsConcurrentSegmentSearch()`](https://github.com/opensearch-project/OpenSearch/blob/bb38ed4836496ac70258c2472668325a012ea3ed/server/src/main/java/org/opensearch/search/aggregations/AggregatorFactory.java#L121) 方法,用于指示给定的聚合类型是否支持并发段搜索。默认情况下,该方法返回 `false`。任何需要支持并发段搜索的聚合器都必须在其自己的工厂实现中重写该方法。 + +为确保基于插件的自定义 `Aggregator` 实现能够在并发搜索路径中正常工作,插件开发者可以在启用并发搜索的情况下验证其实现,然后更新插件,重写 [`supportsConcurrentSegmentSearch()`](https://github.com/opensearch-project/OpenSearch/blob/bb38ed4836496ac70258c2472668325a012ea3ed/server/src/main/java/org/opensearch/search/aggregations/AggregatorFactory.java#L121) 方法使其返回 `true`。 diff --git a/i18n/zh/search-plugins/conversational-search.md b/i18n/zh/search-plugins/conversational-search.md new file mode 100644 index 00000000..45185b05 --- /dev/null +++ b/i18n/zh/search-plugins/conversational-search.md @@ -0,0 +1,433 @@ +--- +title: 对话式搜索 +--- + +# 对话式搜索 + +对话式搜索(conversational search)允许你用自然语言提问,并通过追问来完善答案。这样,对话就成为你与大语言模型(large language model,LLM)之间的交流。为此,模型不能孤立地回答每个问题,而需要记住整个对话的上下文。 + +对话式搜索通过以下组件实现: + +- [对话历史](#conversation-history):使 LLM 能够记住当前对话的上下文并理解追问。 +- [检索增强生成(RAG)](#rag):使 LLM 能够利用专有信息或最新信息补充其静态知识库。 + +## 对话历史 + +对话历史由一个类似 CRUD 的简单 API 构成,包含两种资源:*记忆*(memory)和*消息*(message)。当前对话的所有消息都存储在一个对话*记忆*中。一条*消息*表示一个问答对:人类输入的问题和 AI 的回答。消息不能单独存在,必须添加到某个记忆中。 + +## RAG + +RAG 从索引和历史记录中检索数据,并将所有信息作为上下文发送给 LLM。随后,LLM 使用动态检索到的数据补充其静态知识库。在 OpenSearch 中,RAG 通过包含[检索增强生成处理器](/search-plugins/search-pipelines/rag-processor)的搜索管道(search pipeline)实现。该处理器会拦截 OpenSearch 查询结果,从对话记忆中检索该对话之前的消息,并向 LLM 发送提示词(prompt)。处理器收到 LLM 的响应后,会将响应保存到对话记忆中,并同时返回原始 OpenSearch 查询结果和 LLM 响应。 + +::: danger 警告 +截至 OpenSearch 2.11,RAG 技术仅在 OpenAI 模型和 Amazon Bedrock 上的 Anthropic Claude 模型上进行过测试。 +::: + +::: info 注意 +启用安全插件后,所有记忆都处于 `private` 安全模式。只有创建记忆的用户才能与该记忆交互,任何用户都无法看到其他用户的记忆。 +::: + +## 先决条件 + +要开始使用对话式搜索,请启用对话记忆和 RAG 管道功能: + +```json +PUT /_cluster/settings +{ + "persistent": { + "plugins.ml_commons.memory_feature_enabled": true, + "plugins.ml_commons.rag_pipeline_feature_enabled": true + } +} +``` + +## 使用对话式搜索 + +要使用对话式搜索,请按以下步骤操作: + +1. [创建连接到模型的连接器](#step-1-create-a-connector-to-a-model)。 +1. [注册并部署模型](#step-2-register-and-deploy-the-model) +1. [创建搜索管道](#step-3-create-a-search-pipeline)。 +1. [将 RAG 数据摄取到索引中](#step-4-ingest-rag-data-into-an-index)。 +1. [创建对话记忆](#step-5-create-a-conversation-memory)。 +1. [使用管道进行 RAG](#step-6-use-the-pipeline-for-rag)。 + +### 第 1 步:创建连接到模型的连接器 + +RAG 需要 LLM 才能工作。要连接到 LLM,请创建一个[连接器](/ml-commons-plugin/remote-models/connectors)(connector)。以下请求为 OpenAI GPT 3.5 模型创建一个连接器: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "OpenAI Chat Connector", + "description": "The connector to public OpenAI model service for GPT 3.5", + "version": 2, + "protocol": "http", + "parameters": { + "endpoint": "api.openai.com", + "model": "gpt-3.5-turbo", + "temperature": 0 + }, + "credential": { + "openAI_key": "" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://${parameters.endpoint}/v1/chat/completions", + "headers": { + "Authorization": "Bearer ${credential.openAI_key}" + }, + "request_body": """{ "model": "${parameters.model}", "messages": ${parameters.messages}, "temperature": ${parameters.temperature} }""" + } + ] +} +``` + +OpenSearch 会返回该连接器的连接器 ID: + +```json +{ + "connector_id": "u3DEbI0BfUsSoeNTti-1" +} +``` + +::: tip 提示 +有关连接到其他服务和模型的示例请求,请参阅[连接器蓝图](/ml-commons-plugin/remote-models/blueprints)。 +::: + +### 第 2 步:注册并部署模型 + +注册你在上一步中为其创建了连接器的 LLM。要在 OpenSearch 中注册该模型,请提供上一步返回的 `connector_id`: + +```json +POST /_plugins/_ml/models/_register +{ + "name": "openAI-gpt-3.5-turbo", + "function_name": "remote", + "description": "test model", + "connector_id": "u3DEbI0BfUsSoeNTti-1" +} +``` + +OpenSearch 会返回注册任务的任务 ID 和已注册模型的模型 ID: + +```json +{ + "task_id": "gXDIbI0BfUsSoeNT_jAb", + "status": "CREATED", + "model_id": "gnDIbI0BfUsSoeNT_jAw" +} +``` + +要验证注册是否完成,请调用 Tasks API: + +```json +GET /_plugins/_ml/tasks/gXDIbI0BfUsSoeNT_jAb +``` + +响应中的 `state` 会变为 `COMPLETED`: + +```json +{ + "model_id": "gnDIbI0BfUsSoeNT_jAw", + "task_type": "REGISTER_MODEL", + "function_name": "REMOTE", + "state": "COMPLETED", + "worker_node": [ + "kYv-Z5-mQ4uCUy_cRC6LXA" + ], + "create_time": 1706927128091, + "last_update_time": 1706927128125, + "is_async": false +} +``` + +要部署模型,请向 Deploy API 提供 `model_id`: + +```json +POST /_plugins/_ml/models/gnDIbI0BfUsSoeNT_jAw/_deploy +``` + +OpenSearch 会确认模型已部署: + +```json +{ + "task_id": "cnDObI0BfUsSoeNTDzGd", + "task_type": "DEPLOY_MODEL", + "status": "COMPLETED" +} +``` + +### 第 3 步:创建搜索管道 + +接下来,创建一个包含 `retrieval_augmented_generation` 处理器的搜索管道: + +```json +PUT /_search/pipeline/rag_pipeline +{ + "response_processors": [ + { + "retrieval_augmented_generation": { + "tag": "openai_pipeline_demo", + "description": "Demo pipeline Using OpenAI Connector", + "model_id": "gnDIbI0BfUsSoeNT_jAw", + "context_field_list": ["text"], + "system_prompt": "You are a helpful assistant", + "user_instructions": "Generate a concise and informative answer in less than 100 words for the given question" + } + } + ] +} +``` + +有关处理器字段的信息,请参阅[检索增强生成处理器](/search-plugins/search-pipelines/rag-processor)。 + +### 第 4 步:将 RAG 数据摄取到索引中 + +RAG 会用一些补充数据来增强 LLM 的知识。 + +首先,创建一个用于存储这些数据的索引,并将默认搜索管道设置为上一步创建的管道: + +```json +PUT /my_rag_test_data +{ + "settings": { + "index.search.default_pipeline" : "rag_pipeline" + }, + "mappings": { + "properties": { + "text": { + "type": "text" + } + } + } +} +``` + +接下来,将补充数据摄取到索引中: + +```json +POST _bulk +{"index": {"_index": "my_rag_test_data", "_id": "1"}} +{"text": "Abraham Lincoln was born on February 12, 1809, the second child of Thomas Lincoln and Nancy Hanks Lincoln, in a log cabin on Sinking Spring Farm near Hodgenville, Kentucky.[2] He was a descendant of Samuel Lincoln, an Englishman who migrated from Hingham, Norfolk, to its namesake, Hingham, Massachusetts, in 1638. The family then migrated west, passing through New Jersey, Pennsylvania, and Virginia.[3] Lincoln was also a descendant of the Harrison family of Virginia; his paternal grandfather and namesake, Captain Abraham Lincoln and wife Bathsheba (née Herring) moved the family from Virginia to Jefferson County, Kentucky.[b] The captain was killed in an Indian raid in 1786.[5] His children, including eight-year-old Thomas, Abraham's father, witnessed the attack.[6][c] Thomas then worked at odd jobs in Kentucky and Tennessee before the family settled in Hardin County, Kentucky, in the early 1800s."} +{"index": {"_index": "my_rag_test_data", "_id": "2"}} +{"text": "Chart and table of population level and growth rate for the New York City metro area from 1950 to 2023. United Nations population projections are also included through the year 2035.\\nThe current metro area population of New York City in 2023 is 18,937,000, a 0.37% increase from 2022.\\nThe metro area population of New York City in 2022 was 18,867,000, a 0.23% increase from 2021.\\nThe metro area population of New York City in 2021 was 18,823,000, a 0.1% increase from 2020.\\nThe metro area population of New York City in 2020 was 18,804,000, a 0.01% decline from 2019."} +``` + +## RAG 管道 + +RAG 是一种技术:它从索引中检索文档,将其传递给 seq2seq 模型(例如 LLM),然后在上下文中使用动态检索到的数据补充 LLM 的静态信息。 + +::: danger 警告 +截至 OpenSearch 2.12,RAG 技术仅在 OpenAI 模型、Amazon Bedrock 上的 Anthropic Claude 模型以及 Cohere Command 模型上进行过测试。 +::: + +要配置 Cohere Command 模型以启用 RAG,需要使用后处理函数来转换模型输出。有关更多信息,请参阅 [Cohere RAG 教程](https://github.com/opensearch-project/ml-commons/blob/2.x/docs/tutorials/conversational_search/conversational_search_with_Cohere_Command.md)。 + +### 启用 RAG + +### 第 5 步:创建对话记忆 + +你需要创建一个对话记忆,用于存储对话中的所有消息。为了便于识别该记忆,请在可选的 `name` 字段中为其提供一个名称,如下例所示。由于 `name` 参数不可更新,这是你为对话命名的唯一机会。 + +```json +POST /_plugins/_ml/memory/ +{ + "name": "Conversation about NYC population" +} +``` + +OpenSearch 会返回新建记忆的记忆 ID: + +```json +{ + "memory_id": "znCqcI0BfUsSoeNTntd7" +} +``` + +你将使用 `memory_id` 向该记忆中添加消息。 + +### 第 6 步:使用管道进行 RAG + +要使用 RAG 管道,请向 OpenSearch 发送查询,并在 `ext.generative_qa_parameters` 对象中提供附加参数。 + +`generative_qa_parameters` 对象支持以下参数。 + +参数 | 必需 | 描述 +:--- | :--- | :--- +`llm_question` | 是 | LLM 必须回答的问题。 +`llm_model` | 否 | 当你希望使用其他模型时(例如使用 GPT 4 而不是 GPT 3.5),覆盖连接中设置的原始模型。如果在创建管道时未设置默认模型,则该选项为必需。 +`memory_id` | 否 | 如果提供了 `memory_id`,管道会检索指定记忆中最近的 10 条消息,并将其添加到 LLM 提示词中。如果未指定 `memory_id`,则不会将之前的上下文添加到 LLM 提示词中。 +`context_size` | 否 | 发送给 LLM 的搜索结果数量。通常需要设置该参数以满足词元(token)数量限制,该限制因模型而异。或者,你也可以使用 Search API 中的 `size` 参数来控制发送给 LLM 的搜索结果数量。 +`message_size` | 否 | 发送给 LLM 的消息数量。与搜索结果数量类似,它会影响 LLM 接收的词元总数。未设置时,管道使用默认消息数 `10`。 +`timeout` | 否 | 管道等待通过连接器访问的远程模型响应的秒数。默认值为 `30`。 + +::: info 注意 +如果你的 LLM 设有词元限制,请在 OpenSearch 查询中设置 `size` 字段,以限制搜索响应中使用的文档数量。否则,RAG 管道会将搜索结果中的每个文档都发送给 LLM。 +::: + +如果你向 LLM 询问有关当下的问题,它无法给出答案,因为它是基于几年前的数据训练的。但是,如果你将最新信息作为上下文添加进来,LLM 就能生成响应。例如,你可以询问 LLM 2023 年纽约市都会区的人口。你将构造一个包含 OpenSearch match 查询和 LLM 查询的查询。请提供 `memory_id`,以便将消息存储到相应的记忆对象中: + +```json +GET /my_rag_test_data/_search +{ + "query": { + "match": { + "text": "What's the population of NYC metro area in 2023" + } + }, + "ext": { + "generative_qa_parameters": { + "llm_model": "gpt-3.5-turbo", + "llm_question": "What's the population of NYC metro area in 2023", + "memory_id": "znCqcI0BfUsSoeNTntd7", + "context_size": 5, + "message_size": 5, + "timeout": 15 + } + } +} +``` + +由于上下文中包含一个记录纽约市人口信息的文档,LLM 能够正确回答该问题(不过答案中包含了「projected」(预计)一词,因为它是基于前几年的数据训练的)。响应中包含来自补充 RAG 数据的匹配文档以及 LLM 响应: + +
+ + 响应 + + +```json +{ + "took": 1, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 5.781642, + "hits": [ + { + "_index": "my_rag_test_data", + "_id": "2", + "_score": 5.781642, + "_source": { + "text": """Chart and table of population level and growth rate for the New York City metro area from 1950 to 2023. United Nations population projections are also included through the year 2035.\nThe current metro area population of New York City in 2023 is 18,937,000, a 0.37% increase from 2022.\nThe metro area population of New York City in 2022 was 18,867,000, a 0.23% increase from 2021.\nThe metro area population of New York City in 2021 was 18,823,000, a 0.1% increase from 2020.\nThe metro area population of New York City in 2020 was 18,804,000, a 0.01% decline from 2019.""" + } + }, + { + "_index": "my_rag_test_data", + "_id": "1", + "_score": 0.9782871, + "_source": { + "text": "Abraham Lincoln was born on February 12, 1809, the second child of Thomas Lincoln and Nancy Hanks Lincoln, in a log cabin on Sinking Spring Farm near Hodgenville, Kentucky.[2] He was a descendant of Samuel Lincoln, an Englishman who migrated from Hingham, Norfolk, to its namesake, Hingham, Massachusetts, in 1638. The family then migrated west, passing through New Jersey, Pennsylvania, and Virginia.[3] Lincoln was also a descendant of the Harrison family of Virginia; his paternal grandfather and namesake, Captain Abraham Lincoln and wife Bathsheba (née Herring) moved the family from Virginia to Jefferson County, Kentucky.[b] The captain was killed in an Indian raid in 1786.[5] His children, including eight-year-old Thomas, Abraham's father, witnessed the attack.[6][c] Thomas then worked at odd jobs in Kentucky and Tennessee before the family settled in Hardin County, Kentucky, in the early 1800s." + } + } + ] + }, + "ext": { + "retrieval_augmented_generation": { + "answer": "The population of the New York City metro area in 2023 is projected to be 18,937,000.", + "message_id": "x3CecI0BfUsSoeNT9tV9" + } + } +} +``` +
+ +现在,你将在同一对话中向 LLM 提出一个追问。同样,在请求中提供 `memory_id`: + +```json +GET /my_rag_test_data/_search +{ + "query": { + "match": { + "text": "What was it in 2022" + } + }, + "ext": { + "generative_qa_parameters": { + "llm_model": "gpt-3.5-turbo", + "llm_question": "What was it in 2022", + "memory_id": "znCqcI0BfUsSoeNTntd7", + "context_size": 5, + "message_size": 5, + "timeout": 15 + } + } +} +``` + +LLM 正确识别了对话主题,并返回了相关的响应: + +```json +{ + ... + "ext": { + "retrieval_augmented_generation": { + "answer": "The population of the New York City metro area in 2022 was 18,867,000.", + "message_id": "p3CvcI0BfUsSoeNTj9iH" + } + } +} +``` + +要验证两条消息是否都已添加到记忆中,请向 Get Messages API 提供 `memory_ID`: + +```json +GET /_plugins/_ml/memory/znCqcI0BfUsSoeNTntd7/messages +``` + +响应中包含这两条消息: + +
+ + 响应 + + +```json +{ + "messages": [ + { + "memory_id": "znCqcI0BfUsSoeNTntd7", + "message_id": "x3CecI0BfUsSoeNT9tV9", + "create_time": "2024-02-03T20:33:50.754708446Z", + "input": "What's the population of NYC metro area in 2023", + "prompt_template": """[{"role":"system","content":"You are a helpful assistant"},{"role":"user","content":"Generate a concise and informative answer in less than 100 words for the given question"}]""", + "response": "The population of the New York City metro area in 2023 is projected to be 18,937,000.", + "origin": "retrieval_augmented_generation", + "additional_info": { + "metadata": """["Chart and table of population level and growth rate for the New York City metro area from 1950 to 2023. United Nations population projections are also included through the year 2035.\\nThe current metro area population of New York City in 2023 is 18,937,000, a 0.37% increase from 2022.\\nThe metro area population of New York City in 2022 was 18,867,000, a 0.23% increase from 2021.\\nThe metro area population of New York City in 2021 was 18,823,000, a 0.1% increase from 2020.\\nThe metro area population of New York City in 2020 was 18,804,000, a 0.01% decline from 2019.","Abraham Lincoln was born on February 12, 1809, the second child of Thomas Lincoln and Nancy Hanks Lincoln, in a log cabin on Sinking Spring Farm near Hodgenville, Kentucky.[2] He was a descendant of Samuel Lincoln, an Englishman who migrated from Hingham, Norfolk, to its namesake, Hingham, Massachusetts, in 1638. The family then migrated west, passing through New Jersey, Pennsylvania, and Virginia.[3] Lincoln was also a descendant of the Harrison family of Virginia; his paternal grandfather and namesake, Captain Abraham Lincoln and wife Bathsheba (née Herring) moved the family from Virginia to Jefferson County, Kentucky.[b] The captain was killed in an Indian raid in 1786.[5] His children, including eight-year-old Thomas, Abraham's father, witnessed the attack.[6][c] Thomas then worked at odd jobs in Kentucky and Tennessee before the family settled in Hardin County, Kentucky, in the early 1800s."]""" + } + }, + { + "memory_id": "znCqcI0BfUsSoeNTntd7", + "message_id": "p3CvcI0BfUsSoeNTj9iH", + "create_time": "2024-02-03T20:36:10.24453505Z", + "input": "What was it in 2022", + "prompt_template": """[{"role":"system","content":"You are a helpful assistant"},{"role":"user","content":"Generate a concise and informative answer in less than 100 words for the given question"}]""", + "response": "The population of the New York City metro area in 2022 was 18,867,000.", + "origin": "retrieval_augmented_generation", + "additional_info": { + "metadata": """["Chart and table of population level and growth rate for the New York City metro area from 1950 to 2023. United Nations population projections are also included through the year 2035.\\nThe current metro area population of New York City in 2023 is 18,937,000, a 0.37% increase from 2022.\\nThe metro area population of New York City in 2022 was 18,867,000, a 0.23% increase from 2021.\\nThe metro area population of New York City in 2021 was 18,823,000, a 0.1% increase from 2020.\\nThe metro area population of New York City in 2020 was 18,804,000, a 0.01% decline from 2019.","Abraham Lincoln was born on February 12, 1809, the second child of Thomas Lincoln and Nancy Hanks Lincoln, in a log cabin on Sinking Spring Farm near Hodgenville, Kentucky.[2] He was a descendant of Samuel Lincoln, an Englishman who migrated from Hingham, Norfolk, to its namesake, Hingham, Massachusetts, in 1638. The family then migrated west, passing through New Jersey, Pennsylvania, and Virginia.[3] Lincoln was also a descendant of the Harrison family of Virginia; his paternal grandfather and namesake, Captain Abraham Lincoln and wife Bathsheba (née Herring) moved the family from Virginia to Jefferson County, Kentucky.[b] The captain was killed in an Indian raid in 1786.[5] His children, including eight-year-old Thomas, Abraham's father, witnessed the attack.[6][c] Thomas then worked at odd jobs in Kentucky and Tennessee before the family settled in Hardin County, Kentucky, in the early 1800s."]""" + } + } + ] +} +``` +
+ +## 后续步骤 + +- 要了解有关连接外部平台上的模型的更多信息,请参阅[连接器](/ml-commons-plugin/remote-models/connectors)。 +- 有关支持的 API,请参阅 [Memory API](/ml-commons-plugin/api/memory-apis/)。 +- 要了解有关搜索管道和处理器的更多信息,请参阅[搜索管道](/search-plugins/search-pipelines/)。 +- 有关可用的 OpenSearch 查询,请参阅 [Query DSL](/query-dsl/)。 diff --git a/i18n/zh/search-plugins/hybrid-search.md b/i18n/zh/search-plugins/hybrid-search.md new file mode 100644 index 00000000..182247cd --- /dev/null +++ b/i18n/zh/search-plugins/hybrid-search.md @@ -0,0 +1,209 @@ +--- +title: 混合搜索 +--- + +# 混合搜索 + + +混合搜索(hybrid search)结合了关键词搜索和神经搜索,以提升搜索相关性。要实现混合搜索,你需要设置一个在搜索时运行的[搜索管道](/search-plugins/search-pipelines/)(search pipeline)。你将配置的搜索管道会在中间阶段拦截搜索结果,并对其应用 [`normalization_processor`](/search-plugins/search-pipelines/normalization-processor)。`normalization_processor` 会对来自多个查询子句的文档评分进行归一化和组合,并根据所选的归一化方法和组合方法对文档重新评分。 + +::: info 注意 +**先决条件**
+使用混合搜索之前,必须先设置文本嵌入模型。有关更多信息,请参阅[选择模型](/ml-commons-plugin/integrating-ml-models#choosing-a-model)。 +::: + +## 使用混合搜索 + +要使用混合搜索,请按以下步骤操作: + +1. [创建摄取管道](#step-1-create-an-ingest-pipeline)。 +1. [创建用于摄取的索引](#step-2-create-an-index-for-ingestion)。 +1. [将文档摄取到索引中](#step-3-ingest-documents-into-the-index)。 +1. [配置搜索管道](#step-4-configure-a-search-pipeline)。 +1. [使用混合搜索搜索索引](#step-5-search-the-index-using-hybrid-search)。 + +## 第 1 步:创建摄取管道 + +要生成向量嵌入,你需要创建一个包含 [`text_embedding` 处理器](/ingest-pipelines/processors/text-embedding)的[摄取管道](/api-reference/ingest-apis/)(ingest pipeline),该处理器会将文档字段中的文本转换为向量嵌入。处理器的 `field_map` 决定了用于生成向量嵌入的输入字段,以及存储嵌入的输出字段。 + +以下示例请求创建一个摄取管道,它将 `passage_text` 中的文本转换为文本嵌入,并将嵌入存储在 `passage_embedding` 中: + +```json +PUT /_ingest/pipeline/nlp-ingest-pipeline +{ + "description": "A text embedding pipeline", + "processors": [ + { + "text_embedding": { + "model_id": "bQ1J8ooBpBj3wT4HVUsb", + "field_map": { + "passage_text": "passage_embedding" + } + } + } + ] +} +``` + +## 第 2 步:创建用于摄取的索引 + +为了使用管道中定义的文本嵌入处理器,请创建一个 k-NN 索引,并将上一步创建的管道添加为默认管道。确保 `field_map` 中定义的字段映射为正确的类型。继续以上示例,`passage_embedding` 字段必须映射为 k-NN 向量,且其维度与模型维度一致。同样,`passage_text` 字段应映射为 `text`。 + +以下示例请求创建一个设置了默认摄取管道的 k-NN 索引: + +```json +PUT /my-nlp-index +{ + "settings": { + "index.knn": true, + "default_pipeline": "nlp-ingest-pipeline" + }, + "mappings": { + "properties": { + "id": { + "type": "text" + }, + "passage_embedding": { + "type": "knn_vector", + "dimension": 768, + "method": { + "engine": "lucene", + "space_type": "l2", + "name": "hnsw", + "parameters": {} + } + }, + "passage_text": { + "type": "text" + } + } + } +} +``` + +有关创建 k-NN 索引和使用支持的方法的更多信息,请参阅 [k-NN 索引](/search-plugins/knn/knn-index)。 + +## 第 3 步:将文档摄取到索引中 + +要将文档摄取到上一步创建的索引中,请发送以下请求: + +```json +PUT /my-nlp-index/_doc/1 +{ + "passage_text": "Hello world", + "id": "s1" +} +``` + +```json +PUT /my-nlp-index/_doc/2 +{ + "passage_text": "Hi planet", + "id": "s2" +} +``` + +在文档被摄取到索引之前,摄取管道会对文档运行 `text_embedding` 处理器,为 `passage_text` 字段生成文本嵌入。被索引的文档包含存放原始文本的 `passage_text` 字段,以及存放向量嵌入的 `passage_embedding` 字段。 + +## 第 4 步:配置搜索管道 + +要配置带有 [`normalization-processor`](/search-plugins/search-pipelines/normalization-processor) 的搜索管道,请使用以下请求。处理器中的归一化方法设置为 `min_max`,组合方法设置为 `arithmetic_mean`。`weights` 数组以小数形式的百分比指定分配给每个查询子句的权重: + +```json +PUT /_search/pipeline/nlp-search-pipeline +{ + "description": "Post processor for hybrid search", + "phase_results_processors": [ + { + "normalization-processor": { + "normalization": { + "technique": "min_max" + }, + "combination": { + "technique": "arithmetic_mean", + "parameters": { + "weights": [ + 0.3, + 0.7 + ] + } + } + } + } + ] +} +``` + +## 第 5 步:使用混合搜索搜索索引 + +要对索引执行混合搜索,请使用 [`hybrid` 查询](/query-dsl/compound/hybrid),它会组合关键词搜索和语义搜索的结果。 + +以下示例请求组合了两个查询子句——一个神经查询和一个 `match` 查询。它将上一步创建的搜索管道指定为查询参数: + +```json +GET /my-nlp-index/_search?search_pipeline=nlp-search-pipeline +{ + "_source": { + "exclude": [ + "passage_embedding" + ] + }, + "query": { + "hybrid": { + "queries": [ + { + "match": { + "text": { + "query": "Hi world" + } + } + }, + { + "neural": { + "passage_embedding": { + "query_text": "Hi world", + "model_id": "aVeif4oB5Vm0Tdw8zYO2", + "k": 5 + } + } + } + ] + } + } +} +``` + +或者,你也可以为 `my-nlp-index` 索引设置默认搜索管道。有关更多信息,请参阅[默认搜索管道](/search-plugins/search-pipelines/using-search-pipeline#default-search-pipeline)。 + +响应中包含匹配的文档: + +```json +{ + "took" : 36, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 1.2251667, + "hits" : [ + { + "_index" : "my-nlp-index", + "_id" : "1", + "_score" : 1.2251667, + "_source" : { + "passage_text" : "Hello world", + "id" : "s1" + } + } + ] + } +} +``` diff --git a/i18n/zh/search-plugins/improving-search-performance.md b/i18n/zh/search-plugins/improving-search-performance.md new file mode 100644 index 00000000..945daefe --- /dev/null +++ b/i18n/zh/search-plugins/improving-search-performance.md @@ -0,0 +1,11 @@ +--- +title: 提升搜索性能 +--- + +# 提升搜索性能 + +OpenSearch 提供了多种提升搜索性能的方式: + +- 使用[异步搜索](/search-plugins/async/)以异步方式运行资源密集型查询。 + +- 使用[并发段搜索](/search-plugins/concurrent-segment-search)并发搜索各个段。 diff --git a/i18n/zh/search-plugins/index.md b/i18n/zh/search-plugins/index.md new file mode 100644 index 00000000..607dd75e --- /dev/null +++ b/i18n/zh/search-plugins/index.md @@ -0,0 +1,78 @@ +--- +title: 搜索 +--- + +# 搜索 + +OpenSearch 提供了许多功能,可用于定制搜索场景并提升搜索相关性。 + +## 搜索方法 + +OpenSearch 支持以下搜索方法: + +- **传统词法搜索** + + - [关键词(BM25)搜索](/search-plugins/keyword-search):在文档语料库中搜索查询中出现的词。 + +- **机器学习(ML)驱动的搜索** + + - **向量搜索** + + - [k-NN 搜索](/search-plugins/knn/):在向量索引中搜索与搜索词最邻近的 k 个邻居(k-nearest neighbors)。 + + - **神经搜索**:[神经搜索](/search-plugins/neural-search)支持在摄取时生成向量嵌入,并在搜索时对其进行搜索。神经搜索允许你将 ML 模型集成到搜索中,并可作为实现其他搜索方法的框架。以下搜索方法均基于神经搜索构建: + + - [语义搜索](/search-plugins/semantic-search):考虑搜索上下文中词语的含义。使用基于文本嵌入模型的稠密检索来搜索文本数据。 + + - [多模态搜索](/search-plugins/multimodal-search):使用多模态嵌入模型搜索文本和图像数据。 + + - [神经稀疏搜索](/search-plugins/neural-sparse-search):使用基于稀疏嵌入模型的稀疏检索来搜索文本数据。 + + - [混合搜索](/search-plugins/hybrid-search):结合传统搜索和向量搜索来提升搜索相关性。 + + - [对话式搜索](/search-plugins/conversational-search):实现检索增强的生成式搜索。 + +## 查询语言 + +在 OpenSearch 中,你可以使用以下查询语言搜索数据: + +- [查询领域特定语言(DSL)](/query-dsl/):OpenSearch 的主要查询语言,支持创建复杂且可完全自定义的查询。 + +- [查询字符串查询语言](/query-dsl/full-text/query-string):一种精简的查询语言,可以在搜索请求的查询参数中或 OpenSearch Dashboards 中使用。 + +- [SQL](/search-plugins/sql/sql/):一种传统查询语言,弥合了传统关系型数据库概念与 OpenSearch 面向文档的灵活数据存储之间的差距。 + +- [管道处理语言(PPL)](/search-plugins/sql/ppl/):OpenSearch 中可观测性功能使用的主要语言。PPL 使用管道语法,将多个命令串联成一个查询。 + +- [Dashboards 查询语言(DQL)](/dashboards/dql):一种简单的基于文本的查询语言,用于在 OpenSearch Dashboards 中过滤数据。 + +## 搜索性能 + +OpenSearch 提供了多种提升搜索性能的方式: + +- [异步搜索](/search-plugins/async/):以异步方式运行资源密集型查询。 + +- [并发段搜索](/search-plugins/concurrent-segment-search):并发搜索各个段。 + +## 搜索相关性 + +OpenSearch 提供以下搜索相关性功能: + +- [比较搜索结果](/search-plugins/search-relevance/compare-search-results):OpenSearch Dashboards 中的一个搜索比较工具,可用于并排比较两个查询的结果。 + +- [Querqy](/search-plugins/querqy/):提供查询重写功能。 + +## 搜索结果 + +OpenSearch 支持以下常用的搜索结果操作: + +- [分页](/search-plugins/searching-data/paginate) +- [使用时间点(PIT)分页](/search-plugins/searching-data/point-in-time) +- [排序](/search-plugins/searching-data/sort) +- [高亮搜索词](/search-plugins/searching-data/highlight) +- [自动补全](/search-plugins/searching-data/autocomplete) +- [拼写纠错(did-you-mean)](/search-plugins/searching-data/did-you-mean) + +## 搜索管道 + +你可以使用[搜索管道](/search-plugins/search-pipelines/)处理搜索查询和搜索结果。 diff --git a/i18n/zh/search-plugins/keyword-search.md b/i18n/zh/search-plugins/keyword-search.md new file mode 100644 index 00000000..f69d84f0 --- /dev/null +++ b/i18n/zh/search-plugins/keyword-search.md @@ -0,0 +1,176 @@ +--- +title: 关键词搜索 +--- + +# 关键词搜索 + +默认情况下,OpenSearch 使用 [Okapi BM25](https://en.wikipedia.org/wiki/Okapi_BM25) 算法计算文档评分。BM25 是一种基于关键词的算法,它针对查询中出现的词执行词法搜索。 + +在确定文档的相关性时,BM25 会考虑[词频/逆文档频率(TF/IDF)](https://en.wikipedia.org/wiki/Tf%E2%80%93idf): + +- *词频*(term frequency)规定,搜索词出现频率越高的文档相关性越高。 + +- *逆文档频率*(inverse document frequency)会降低在语料库所有文档中普遍出现的词(例如 "the" 这样的冠词)的权重。 + +## 示例 + +以下示例查询在 `shakespeare` 索引中搜索词 `long live king`: + +```json +GET shakespeare/_search +{ + "query": { + "match": { + "text_entry": "long live king" + } + } +} +``` + +响应中包含匹配的文档,每个文档的相关性评分(relevance score)位于 `_score` 字段中: + +```json +{ + "took": 113, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2352, + "relation": "eq" + }, + "max_score": 18.781435, + "hits": [ + { + "_index": "shakespeare", + "_id": "32437", + "_score": 18.781435, + "_source": { + "type": "line", + "line_id": 32438, + "play_name": "Hamlet", + "speech_number": 3, + "line_number": "1.1.3", + "speaker": "BERNARDO", + "text_entry": "Long live the king!" + } + }, + { + "_index": "shakespeare", + "_id": "83798", + "_score": 16.523308, + "_source": { + "type": "line", + "line_id": 83799, + "play_name": "Richard III", + "speech_number": 42, + "line_number": "3.7.242", + "speaker": "BUCKINGHAM", + "text_entry": "Long live Richard, Englands royal king!" + } + }, + { + "_index": "shakespeare", + "_id": "82994", + "_score": 15.588365, + "_source": { + "type": "line", + "line_id": 82995, + "play_name": "Richard III", + "speech_number": 24, + "line_number": "3.1.80", + "speaker": "GLOUCESTER", + "text_entry": "live long." + } + }, + { + "_index": "shakespeare", + "_id": "7199", + "_score": 15.586321, + "_source": { + "type": "line", + "line_id": 7200, + "play_name": "Henry VI Part 2", + "speech_number": 12, + "line_number": "2.2.64", + "speaker": "BOTH", + "text_entry": "Long live our sovereign Richard, Englands king!" + } + } + ... + ] + } +} +``` + +## 相似度算法 + +下表列出了支持的相似度算法。 + +算法 | 描述 +`BM25` | OpenSearch 默认的 [Okapi BM25](https://en.wikipedia.org/wiki/Okapi_BM25) 相似度算法。 +`boolean` | 为词项分配与其权重提升(boost)值相等的评分。如果希望文档评分仅基于词项是否匹配这一二元值,请使用 `boolean` 相似度。 + +## 指定相似度 + +在字段级别配置映射(mapping)时,可以在 `similarity` 参数中指定相似度算法。 + +例如,以下查询为 `boolean_field` 指定 `boolean` 相似度,而 `bm25_field` 使用默认的 `BM25` 相似度: + +```json +PUT /testindex +{ + "mappings": { + "properties": { + "bm25_field": { + "type": "text" + }, + "boolean_field": { + "type": "text", + "similarity": "boolean" + } + } + } +} +``` + +## 配置 BM25 相似度 + +你可以按如下方式在索引级别配置 BM25 相似度参数: + +```json +PUT /testindex +{ + "settings": { + "index": { + "similarity": { + "custom_similarity": { + "type": "BM25", + "k1": 1.2, + "b": 0.75, + "discount_overlaps": "true" + } + } + } + } +} +``` + +`BM25` 相似度支持以下参数。 + +参数 | 数据类型 | 描述 +`k1` | Float | 决定非线性词频归一化(饱和)的特性。默认值为 `1.2`。 +`b` | Float | 决定文档长度对 TF 值进行归一化的程度。默认值为 `0.75`。 +`discount_overlaps` | Boolean | 决定在计算范数时是否忽略重叠词元(位置增量为零的词元)。默认值为 `true`(计算范数时不计入重叠词元)。 + +--- + +## 后续步骤 + +- 了解[查询上下文和过滤上下文](/query-dsl/query-filter-context)。 +- 了解 OpenSearch 支持的[查询类型](/query-dsl/)。 diff --git a/i18n/zh/search-plugins/knn/api.md b/i18n/zh/search-plugins/knn/api.md new file mode 100644 index 00000000..9d1b3650 --- /dev/null +++ b/i18n/zh/search-plugins/knn/api.md @@ -0,0 +1,358 @@ +--- +title: API +--- + +# k-NN 插件 API + +k-NN 插件添加了多个 API,用于管理、监控和优化 k-NN 工作负载。 + +## 统计信息 + + +k-NN `stats` API 提供有关 k-NN 插件当前状态的信息。该插件会跟踪集群级和节点级的统计信息。集群级统计信息对整个集群只有一个值,节点级统计信息对集群中的每个节点各有一个值。你可以按 `nodeId` 和 `statName` 过滤查询: +``` +GET /_plugins/_knn/nodeId1,nodeId2/stats/statName1,statName2 +``` + +统计项 | 描述 +:--- | :--- +`circuit_breaker_triggered` | 表示断路器是否已触发。该统计项仅与近似 k-NN 搜索相关。 +`total_load_time` | k-NN 将原生库索引加载到缓存中所花费的时间,单位为纳秒。该统计项仅与近似 k-NN 搜索相关。 +`eviction_count` | 由于内存限制或空闲时间而被逐出缓存的原生库索引数量。该统计项仅与近似 k-NN 搜索相关。
**注意**:因删除索引而发生的显式逐出不计入在内。 +`hit_count` | 缓存命中次数。当用户查询已加载到内存中的原生库索引时,即发生缓存命中。该统计项仅与近似 k-NN 搜索相关。 +`miss_count` | 缓存未命中次数。当用户查询尚未加载到内存中的原生库索引时,即发生缓存未命中。该统计项仅与近似 k-NN 搜索相关。 +`graph_memory_usage` | 节点上原生库索引使用的原生内存量,单位为 KB。 +`graph_memory_usage_percentage` | 节点上原生库索引使用的原生内存量占最大缓存容量的百分比。 +`graph_index_requests` | 将文档的 `knn_vector` 字段添加到原生库索引的请求数。 +`graph_index_errors` | 将文档的 `knn_vector` 字段添加到原生库索引时出错的请求数。 +`graph_query_requests` | 已执行的原生库索引查询数。 +`graph_query_errors` | 出错的原生库索引查询数。 +`knn_query_requests` | 收到的 k-NN 查询请求数。 +`cache_capacity_reached` | 是否已达到 `knn.memory.circuit_breaker.limit`。该统计项仅与近似 k-NN 搜索相关。 +`load_success_count` | k-NN 成功将原生库索引加载到缓存中的次数。该统计项仅与近似 k-NN 搜索相关。 +`load_exception_count` | 尝试将原生库索引加载到缓存时发生异常的次数。该统计项仅与近似 k-NN 搜索相关。 +`indices_in_cache` | 对于每个包含 `knn_vector` 字段并启用了近似 k-NN 的 OpenSearch 索引,该统计项提供该 OpenSearch 索引拥有的原生库索引数量,以及该 OpenSearch 索引使用的 `graph_memory_usage` 总量(单位为 KB)。 +`script_compilations` | k-NN 脚本被编译的次数。该值通常应为 1 或 0,但如果存放已编译脚本的缓存已满,k-NN 脚本可能会被重新编译。该统计项仅与 k-NN 评分脚本搜索相关。 +`script_compilation_errors` | 脚本编译期间发生的错误数。该统计项仅与 k-NN 评分脚本搜索相关。 +`script_query_requests` | 脚本查询总数。该统计项仅与 k-NN 评分脚本搜索相关。 +`script_query_errors` | 脚本查询期间发生的错误数。该统计项仅与 k-NN 评分脚本搜索相关。 +`nmslib_initialized` | 布尔值,表示 *nmslib* JNI 库是否已在该节点上加载并初始化。 +`faiss_initialized` | 布尔值,表示 *faiss* JNI 库是否已在该节点上加载并初始化。 +`model_index_status` | 模型系统索引的状态。有效值为 "red"、"yellow"、"green"。如果该索引不存在,则为 null。 +`indexing_from_model_degraded` | 布尔值,表示基于模型的索引是否已降级。当 JVM 内存不足以缓存模型时会出现这种情况。 +`training_requests` | 向该节点发出的训练请求数。 +`training_errors` | 该节点上发生的训练错误数。 +`training_memory_usage` | 该节点上训练使用的原生内存量,单位为 KB。 +`training_memory_usage_percentage` | 该节点上训练使用的原生内存量占最大缓存容量的百分比。 + +**注意**:某些统计项的名称中包含 *graph*。在这些情况下,*graph* 等同于*原生库索引*。*graph*(图)这一术语是历史遗留的细节,源自该插件仅支持由分层图构成的 HNSW 算法的时期。 + +### 用法 + +```json +GET /_plugins/_knn/stats?pretty +{ + "_nodes" : { + "total" : 1, + "successful" : 1, + "failed" : 0 + }, + "cluster_name" : "my-cluster", + "circuit_breaker_triggered" : false, + "model_index_status" : "YELLOW", + "nodes" : { + "JdfxIkOS1-43UxqNz98nw" : { + "graph_memory_usage_percentage" : 3.68, + "graph_query_requests" : 1420920, + "graph_memory_usage" : 2, + "cache_capacity_reached" : false, + "load_success_count" : 179, + "training_memory_usage" : 0, + "indices_in_cache" : { + "myindex" : { + "graph_memory_usage" : 2, + "graph_memory_usage_percentage" : 3.68, + "graph_count" : 2 + } + }, + "script_query_errors" : 0, + "hit_count" : 1420775, + "knn_query_requests" : 147092, + "total_load_time" : 2436679306, + "miss_count" : 179, + "training_memory_usage_percentage" : 0.0, + "graph_index_requests" : 656, + "faiss_initialized" : true, + "load_exception_count" : 0, + "training_errors" : 0, + "eviction_count" : 0, + "nmslib_initialized" : false, + "script_compilations" : 0, + "script_query_requests" : 0, + "graph_query_errors" : 0, + "indexing_from_model_degraded" : false, + "graph_index_errors" : 0, + "training_requests" : 17, + "script_compilation_errors" : 0 + } + } +} +``` + +```json +GET /_plugins/_knn/HYMrXXsBSamUkcAjhjeN0w/stats/circuit_breaker_triggered,graph_memory_usage?pretty +{ + "_nodes" : { + "total" : 1, + "successful" : 1, + "failed" : 0 + }, + "cluster_name" : "my-cluster", + "circuit_breaker_triggered" : false, + "nodes" : { + "HYMrXXsBSamUkcAjhjeN0w" : { + "graph_memory_usage" : 1 + } + } +} +``` + +## 预热操作 + + +用于执行近似 k 最近邻(k-NN)搜索的原生库索引以特殊文件的形式与其他 Apache Lucene 段文件存储在一起。为了使用 k-NN 插件对这些索引执行搜索,插件需要将这些文件加载到原生内存中。 + +如果插件尚未将这些文件加载到原生内存中,它会在收到搜索请求时加载。加载时间可能导致初始查询出现较高的延迟。为了避免这种情况,用户通常会在预热期间运行随机查询。预热期结束后,文件已加载到原生内存中,即可开始生产工作负载。这种加载过程是间接的,需要额外的工作。 + +作为替代方案,你可以对想要搜索的索引运行 k-NN 插件的预热(warmup)API 操作来避免这一延迟问题。该操作会将请求中指定的所有索引的所有分片(主分片和副本分片)的全部原生库文件加载到原生内存中。 + +该过程完成后,你就可以开始搜索这些索引,而不会产生初始延迟。预热 API 操作是幂等的,因此如果某个段的原生库文件已经加载到内存中,该操作不会产生任何影响。它只会加载当前不在内存中的文件。 + +### 用法 {#usage-1} + +以下请求对三个索引执行预热: + +```json +GET /_plugins/_knn/warmup/index1,index2,index3?pretty +{ + "_shards" : { + "total" : 6, + "successful" : 6, + "failed" : 0 + } +} +``` + +`total` 表示 k-NN 插件尝试预热的分片数量。响应中还包含插件预热成功和失败的分片数量。 + +在预热操作完成或请求超时之前,该调用不会返回结果。如果请求超时,该操作仍会在集群上继续执行。要监控预热操作,请使用 OpenSearch `_tasks` API: + +```json +GET /_tasks +``` + +操作完成后,使用 [k-NN `_stats` API 操作](#stats)查看 k-NN 插件已将哪些内容加载到图中。 + +### 最佳实践 + +为了让预热操作正常工作,请遵循以下最佳实践: + +* 不要对想要预热的索引运行合并操作。在合并期间,k-NN 插件会创建新的段,旧的段有时会被删除。例如,你可能会遇到这样的情况:预热 API 操作将原生库索引 A 和 B 加载到原生内存中,但随后段 A 和 B 合并生成了段 C。此时 A 和 B 的原生库索引将不再位于内存中,而原生库索引 C 也不在内存中。在这种情况下,加载原生库索引 C 的初始开销依然存在。 + +* 确认想要预热的所有原生库索引都能放入原生内存中。有关原生内存限制的更多信息,请参阅 [knn.memory.circuit_breaker.limit 统计项](/search-plugins/knn/settings#cluster-settings)。较高的图内存使用量会导致缓存抖动,从而可能使操作不断失败并反复尝试重新运行。 + +* 不要索引任何想要加载到缓存中的文档。向段中写入新信息会使预热 API 操作在原生库索引变为可搜索之前无法加载它们。这意味着在索引完成后,你必须再次运行预热操作。 + +## 获取模型 + + +用于检索集群中现有模型的信息。某些原生库索引配置需要在开始索引和查询之前执行训练步骤。训练的输出是一个模型,可在索引期间用于初始化原生库索引文件。该模型会被序列化并存储在 k-NN 模型系统索引中。 + +``` +GET /_plugins/_knn/models/{model_id} +``` + +响应字段 | 描述 +:--- | :--- +`model_id` | 所获取模型的 ID。 +`model_blob` | 序列化模型的 base64 编码字符串。 +`state` | 模型的当前状态,取值为 "created"、"failed"、"training" 之一。 +`timestamp` | 模型的创建时间。 +`description` | 用户提供的模型描述。 +`error` | 说明模型为何处于失败状态的错误消息。 +`space_type` | 训练该模型所针对的空间类型。 +`dimension` | 该模型所针对的维度。 +`engine` | 用于创建模型的原生库,取值为 "faiss" 或 "nmslib"。 + +### 用法 {#usage-2} + +```json +GET /_plugins/_knn/models/test-model?pretty +{ + "model_id" : "test-model", + "model_blob" : "SXdGbIAAAAAAAAAAAA...", + "state" : "created", + "timestamp" : "2021-11-15T18:45:07.505369036Z", + "description" : "Default", + "error" : "", + "space_type" : "l2", + "dimension" : 128, + "engine" : "faiss" +} +``` + +```json +GET /_plugins/_knn/models/test-model?pretty&filter_path=model_id,state +{ + "model_id" : "test-model", + "state" : "created" +} +``` + +## 搜索模型 + + +使用 OpenSearch 查询在索引中搜索模型。 + +### 用法 {#usage-3} +```json +GET/POST /_plugins/_knn/models/_search?pretty&_source_excludes=model_blob +{ + "query": { + ... + } +} + +{ + "took" : 0, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : ".opensearch-knn-models", + "_id" : "test-model", + "_score" : 1.0, + "_source" : { + "engine" : "faiss", + "space_type" : "l2", + "description" : "Default", + "model_id" : "test-model", + "state" : "created", + "error" : "", + "dimension" : 128, + "timestamp" : "2021-11-15T18:45:07.505369036Z" + } + } + ] + } +} +``` + +## 删除模型 + + +用于删除集群中的特定模型。 + +### 用法 {#usage-4} + +```json +DELETE /_plugins/_knn/models/{model_id} +{ + "model_id": {model_id}, + "acknowledged": true +} +``` + +## 训练模型 + + +创建并训练一个模型,该模型可在索引期间用于初始化 k-NN 原生库索引。该 API 会从训练索引的 `knn_vector` 字段中提取训练数据,然后创建并训练模型,再将其序列化到模型系统索引中。训练数据必须与请求体中传入的维度一致。该请求会在训练开始时返回。要监控模型的状态,请使用[获取模型 API](#get-model)。 + +查询参数 | 描述 +:--- | :--- +`model_id` | (可选)所获取模型的 ID。如果未指定,将生成一个随机 ID。 +`node_id` | (可选)执行训练的首选节点。如果设置了该参数,并且该节点被认为有能力执行训练,则使用该节点执行训练。 + +请求参数 | 描述 +:--- | :--- +`training_index` | 训练数据来源的索引。 +`training_field` | 从 `training_index` 中获取训练数据的 `knn_vector` 字段。该字段的维度必须与传入该请求的 `dimension` 一致。 +`dimension` | 该模型所针对的维度。 +`max_training_vector_count` | (可选)训练时从训练索引中使用的最大向量数。默认使用索引中的全部向量。 +`search_size` | (可选)训练数据通过滚动查询从训练索引中提取。该参数定义每次滚动查询返回的结果数。默认为 10,000。 +`description` | (可选)用户提供的模型描述。 +`method` | 用于搜索的 ANN 方法的配置。有关可用方法的更多信息,请参阅[方法文档](/search-plugins/knn/knn-index#method-definitions)。该方法必须是需要训练的方法,才视为有效。 + + +### 用法 {#usage-5} + +```json +POST /_plugins/_knn/models/{model_id}/_train?preference={node_id} +{ + "training_index": "train-index-name", + "training_field": "train-field-name", + "dimension": 16, + "max_training_vector_count": 1200, + "search_size": 100, + "description": "My model", + "method": { + "name":"ivf", + "engine":"faiss", + "space_type": "l2", + "parameters":{ + "nlist":128, + "encoder":{ + "name":"pq", + "parameters":{ + "code_size":8 + } + } + } + } +} + +{ + "model_id": "model_x" +} +``` + +```json +POST /_plugins/_knn/models/_train?preference={node_id} +{ + "training_index": "train-index-name", + "training_field": "train-field-name", + "dimension": 16, + "max_training_vector_count": 1200, + "search_size": 100, + "description": "My model", + "method": { + "name":"ivf", + "engine":"faiss", + "space_type": "l2", + "parameters":{ + "nlist":128, + "encoder":{ + "name":"pq", + "parameters":{ + "code_size":8 + } + } + } + } +} + +{ + "model_id": "dcdwscddscsad" +} +``` diff --git a/i18n/zh/search-plugins/knn/approximate-knn.md b/i18n/zh/search-plugins/knn/approximate-knn.md new file mode 100644 index 00000000..1dae085e --- /dev/null +++ b/i18n/zh/search-plugins/knn/approximate-knn.md @@ -0,0 +1,289 @@ +--- +title: 近似 k-NN 搜索 +--- + +# 近似 k-NN 搜索 + +标准的 k-NN 搜索方法使用暴力方式计算相似度,即测量查询与若干个点之间的最近距离,从而得到精确的结果。这在许多应用中效果都很好。但是,对于维度很高的超大型数据集,这种方式会带来扩展性问题,降低搜索效率。近似 k-NN(approximate k-NN)搜索方法可以通过借助一些工具来克服这一问题:这些工具能更高效地重构索引,并降低可搜索向量(vector)的维度。使用这种方法需要牺牲一定的准确性,但可以显著提高搜索处理速度。 + +OpenSearch 所采用的近似 k-NN 搜索方法使用来自 [nmslib](https://github.com/nmslib/nmslib)、[faiss](https://github.com/facebookresearch/faiss) 和 [Lucene](https://lucene.apache.org/) 库的近似最近邻(approximate nearest neighbor,ANN)算法来支持 k-NN 搜索。这些搜索方法利用 ANN 来降低大型数据集的搜索延迟。在 k-NN 插件提供的三种搜索方法中,该方法为大型数据集提供了最好的搜索可扩展性。当数据集达到数十万个向量时,这是首选方法。 + +::: info 注意 +有关插件当前支持的算法的详细信息,请参阅 [k-NN 索引文档](/search-plugins/knn/knn-index#method-definitions)。 +::: + +k-NN 插件在索引期间会为每个 knn-vector 字段/Lucene 段(segment)对构建一个向量的原生库索引,可在搜索期间用于高效地查找与查询向量最邻近的 k 个邻居。要了解有关 Lucene 段的更多信息,请参阅 [Apache Lucene 文档](https://lucene.apache.org/core/8_9_0/core/org/apache/lucene/codecs/lucene87/package-summary.html#package.description)。这些原生库索引会在搜索期间加载到原生内存中,并由缓存进行管理。要了解有关将原生库索引预先加载到内存中的更多信息,请参阅[预热 API](/search-plugins/knn/api#warmup-operation)。此外,你还可以查看哪些原生库索引已经加载到内存中。有关详细信息,请参阅 [stats API 部分](/search-plugins/knn/api#stats)。 + +由于原生库索引是在索引期间构建的,因此无法先对索引应用过滤器再使用该搜索方法。所有过滤器都会应用于近似最近邻搜索产生的结果。 + +## 引擎与集群节点规模的建议 + +近似 k-NN 搜索使用的三种引擎各有特点,因此在特定情况下,某一种引擎会比其他引擎更合适。你可以参考以下一般信息,确定哪种引擎最能满足你的需求。 + +一般来说,nmslib 在搜索方面的性能优于 faiss 和 Lucene。但是,如果要优化索引吞吐量,faiss 是一个不错的选择。对于相对较小的数据集(最多几百万个向量),Lucene 引擎表现出更好的延迟和召回率。同时,与其他引擎相比,它的索引体积最小,因此可以为数据节点使用规格更小的 AWS 实例。 + +在考虑集群节点规模时,一般做法是首先使索引在集群中均匀分布。不过,还需要考虑其他因素。为了帮助你做出这些选择,可以参考 OpenSearch 托管服务指南中的[确定域的规模](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/sizing-domains.html)一节。 + +## 近似 k-NN 入门 + +要使用 k-NN 插件的近似搜索功能,必须首先创建一个 `index.knn` 设置为 `true` 的 k-NN 索引。该设置会让插件为该索引创建原生库索引。 + +接下来,必须添加一个或多个 `knn_vector` 数据类型的字段。以下示例创建一个包含两个 `knn_vector` 字段的索引,其中一个使用 `faiss`,另一个使用 `nmslib`: + +```json +PUT my-knn-index-1 +{ + "settings": { + "index": { + "knn": true, + "knn.algo_param.ef_search": 100 + } + }, + "mappings": { + "properties": { + "my_vector1": { + "type": "knn_vector", + "dimension": 2, + "method": { + "name": "hnsw", + "space_type": "l2", + "engine": "nmslib", + "parameters": { + "ef_construction": 128, + "m": 24 + } + } + }, + "my_vector2": { + "type": "knn_vector", + "dimension": 4, + "method": { + "name": "hnsw", + "space_type": "innerproduct", + "engine": "faiss", + "parameters": { + "ef_construction": 256, + "m": 48 + } + } + } + } + } +} +``` + +在上面的示例中,两个 `knn_vector` 字段都是通过方法定义来配置的。此外,`knn_vector` 字段也可以通过模型来配置。有关详细信息,请参阅 [knn_vector 数据类型](/field-types/supported-field-types/knn-vector)一节。 + +`knn_vector` 数据类型支持浮点数向量,对于 NMSLIB、Faiss 和 Lucene 引擎,其维度数最多可达 16,000,由 dimension 映射参数设置。 + +::: tip 提示 +在 OpenSearch 中,编解码器(codec)负责索引的存储和检索。k-NN 插件使用自定义编解码器将向量数据写入原生库索引,以便底层 k-NN 搜索库能够读取这些数据。 +::: + +创建索引后,就可以向其中添加一些数据: + +```json +POST _bulk +{ "index": { "_index": "my-knn-index-1", "_id": "1" } } +{ "my_vector1": [1.5, 2.5], "price": 12.2 } +{ "index": { "_index": "my-knn-index-1", "_id": "2" } } +{ "my_vector1": [2.5, 3.5], "price": 7.1 } +{ "index": { "_index": "my-knn-index-1", "_id": "3" } } +{ "my_vector1": [3.5, 4.5], "price": 12.9 } +{ "index": { "_index": "my-knn-index-1", "_id": "4" } } +{ "my_vector1": [5.5, 6.5], "price": 1.2 } +{ "index": { "_index": "my-knn-index-1", "_id": "5" } } +{ "my_vector1": [4.5, 5.5], "price": 3.7 } +{ "index": { "_index": "my-knn-index-1", "_id": "6" } } +{ "my_vector2": [1.5, 5.5, 4.5, 6.4], "price": 10.3 } +{ "index": { "_index": "my-knn-index-1", "_id": "7" } } +{ "my_vector2": [2.5, 3.5, 5.6, 6.7], "price": 5.5 } +{ "index": { "_index": "my-knn-index-1", "_id": "8" } } +{ "my_vector2": [4.5, 5.5, 6.7, 3.7], "price": 4.4 } +{ "index": { "_index": "my-knn-index-1", "_id": "9" } } +{ "my_vector2": [1.5, 5.5, 4.5, 6.4], "price": 8.9 } + +``` + +然后,可以使用 `knn` 查询类型对这些数据执行近似最近邻搜索: + +```json +GET my-knn-index-1/_search +{ + "size": 2, + "query": { + "knn": { + "my_vector2": { + "vector": [2, 3, 5, 6], + "k": 2 + } + } + } +} +``` + +`k` 是每个图的搜索所返回的邻居数量。你还必须包含 `size` 选项,它表示查询实际返回的结果数量。插件会为每个分片(以及每个段)返回 `k` 个结果,为整个查询返回 `size` 个结果。插件支持的 `k` 最大值为 10,000。 + +### 基于模型构建 k-NN 索引 + +对于我们支持的某些算法,原生库索引需要经过训练才能使用。对每个新创建的段都进行训练的代价很高,因此我们引入了*模型*(model)的概念,用于在创建段时初始化原生库索引。*模型*是通过调用 [Train API](/search-plugins/knn/api#train-model) 并传入训练数据来源和模型的方法定义来创建的。训练完成后,模型会被序列化到 k-NN 模型系统索引中。之后在索引期间,会从该索引中取出模型来初始化各个段。 + +要训练模型,首先需要一个包含训练数据的 OpenSearch 索引。训练数据可以来自任何维度与要创建的模型维度一致的 `knn_vector` 字段。训练数据可以就是你将要索引的数据,也可以是单独的数据集。下面创建一个训练索引: + +```json +PUT /train-index +{ + "settings": { + "number_of_shards": 3, + "number_of_replicas": 0 + }, + "mappings": { + "properties": { + "train-field": { + "type": "knn_vector", + "dimension": 4 + } + } + } +} +``` + +注意,索引设置中没有设置 `index.knn`。这样可以确保不会为该索引创建原生库索引。 + +现在可以向该索引中添加一些数据: + +```json +POST _bulk +{ "index": { "_index": "train-index", "_id": "1" } } +{ "train-field": [1.5, 5.5, 4.5, 6.4]} +{ "index": { "_index": "train-index", "_id": "2" } } +{ "train-field": [2.5, 3.5, 5.6, 6.7]} +{ "index": { "_index": "train-index", "_id": "3" } } +{ "train-field": [4.5, 5.5, 6.7, 3.7]} +{ "index": { "_index": "train-index", "_id": "4" } } +{ "train-field": [1.5, 5.5, 4.5, 6.4]} +``` + +在训练索引中完成索引后,就可以调用 Train API: + +```json +POST /_plugins/_knn/models/my-model/_train +{ + "training_index": "train-index", + "training_field": "train-field", + "dimension": 4, + "description": "My model description", + "method": { + "name": "ivf", + "engine": "faiss", + "space_type": "l2", + "parameters": { + "nlist": 4, + "nprobes": 2 + } + } +} +``` + +训练作业一启动,Train API 就会立即返回。要检查训练状态,可以使用 Get Model API: + +```json +GET /_plugins/_knn/models/my-model?filter_path=state&pretty +{ + "state": "training" +} +``` + +当模型进入 "created" 状态后,就可以创建一个使用该模型来初始化其原生库索引的索引: + +```json +PUT /target-index +{ + "settings": { + "number_of_shards": 3, + "number_of_replicas": 1, + "index.knn": true + }, + "mappings": { + "properties": { + "target-field": { + "type": "knn_vector", + "model_id": "my-model" + } + } + } +} +``` + +最后,可以将要搜索的文档添加到索引中: +```json +POST _bulk +{ "index": { "_index": "target-index", "_id": "1" } } +{ "target-field": [1.5, 5.5, 4.5, 6.4]} +{ "index": { "_index": "target-index", "_id": "2" } } +{ "target-field": [2.5, 3.5, 5.6, 6.7]} +{ "index": { "_index": "target-index", "_id": "3" } } +{ "target-field": [4.5, 5.5, 6.7, 3.7]} +{ "index": { "_index": "target-index", "_id": "4" } } +{ "target-field": [1.5, 5.5, 4.5, 6.4]} +... +``` + +数据摄取完成后,就可以像搜索其他任何 `knn_vector` 字段一样对其进行搜索! + +### 将近似 k-NN 与过滤器结合使用 + +要了解如何在 k-NN 搜索中使用过滤器,请参阅[带过滤器的 k-NN 搜索](/search-plugins/knn/filter-search-knn)。 + +### 将近似 k-NN 与嵌套字段结合使用 + +要了解如何对嵌套字段使用 k-NN 搜索,请参阅[嵌套字段的 k-NN 搜索](/search-plugins/knn/nested-search-knn)。 + +## 空间 + +空间(space)对应用于测量两点之间距离的函数,以确定 k 个最近邻。从 k-NN 的角度来看,评分越低表示结果越接近、越好。这与 OpenSearch 的评分方式相反:在 OpenSearch 中,评分越高表示结果越好。为了将距离转换为 OpenSearch 评分,我们取 1 / (1 + distance)。k-NN 插件支持以下空间。 + +::: info 注意 +并非每种方法都支持所有这些空间。请务必查看[方法文档](/search-plugins/knn/knn-index#method-definitions),确认你需要的空间是否受支持。 +::: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
spaceType距离函数(d)OpenSearch 评分
l1\[ d(\mathbf{x}, \mathbf{y}) = \sum_{i=1}^n |x_i - y_i| \]\[ score = {1 \over 1 + d } \]
l2\[ d(\mathbf{x}, \mathbf{y}) = \sum_{i=1}^n (x_i - y_i)^2 \]\[ score = {1 \over 1 + d } \]
linf\[ d(\mathbf{x}, \mathbf{y}) = max(|x_i - y_i|) \]\[ score = {1 \over 1 + d } \]
cosinesimil\[ d(\mathbf{x}, \mathbf{y}) = 1 - cos { \theta } = 1 - {\mathbf{x} · \mathbf{y} \over \|\mathbf{x}\| · \|\mathbf{y}\|}\]\[ = 1 - + {\sum_{i=1}^n x_i y_i \over \sqrt{\sum_{i=1}^n x_i^2} · \sqrt{\sum_{i=1}^n y_i^2}}\] + 其中 \(\|\mathbf{x}\|\) 和 \(\|\mathbf{y}\|\) 分别表示向量 x 和 y 的范数。nmslib 和 faiss:\[ score = {1 \over 1 + d } \]
Lucene:\[ score = {2 - d \over 2}\]
innerproduct(Lucene 不支持)\[ d(\mathbf{x}, \mathbf{y}) = - {\mathbf{x} · \mathbf{y}} = - \sum_{i=1}^n x_i y_i \]\[ \text{If} d \ge 0, \] \[score = {1 \over 1 + d }\] \[\text{If} d < 0, score = −d + 1\]
+ +::: info 注意 +余弦相似度公式本身不包含 `1 -` 前缀。但是,由于相似度搜索库将较小的评分视为更接近的结果,因此对于余弦相似度空间,它们返回的是 `1 - cosineSimilarity`——这就是距离函数中包含 `1 -` 的原因。 +::: diff --git a/i18n/zh/search-plugins/knn/filter-search-knn.md b/i18n/zh/search-plugins/knn/filter-search-knn.md new file mode 100644 index 00000000..7a850316 --- /dev/null +++ b/i18n/zh/search-plugins/knn/filter-search-knn.md @@ -0,0 +1,692 @@ +--- +title: 带过滤器的 k-NN 搜索 +--- + +# 带过滤器的 k-NN 搜索 + +为了细化 k-NN 结果,你可以使用以下方法之一对 k-NN 搜索进行过滤: + +- [高效 k-NN 过滤](#efficient-k-nn-filtering):这种方法在 k-NN 搜索*期间*应用过滤,而不是在 k-NN 搜索之前或之后,从而确保返回 `k` 个结果(如果总结果数至少为 `k` 个)。以下引擎支持这种方法: + - 使用分层可导航小世界(Hierarchical Navigable Small World,HNSW)算法的 Lucene 引擎(k-NN 插件 2.4 及更高版本) + - 使用 HNSW 算法(k-NN 插件 2.9 及更高版本)或 IVF 算法(k-NN 插件 2.10 及更高版本)的 Faiss 引擎 + +- [后过滤](#post-filtering):由于过滤在 k-NN 搜索之后执行,对于限制性较强的过滤器,这种方法返回的结果可能远少于 `k` 个。这种方法可以使用以下两种过滤策略: + - [布尔后过滤器](#boolean-filter-with-ann-search):这种方法先运行[近似最近邻(ANN)](/search-plugins/knn/approximate-knn)搜索,然后对结果应用过滤器。两个查询部分独立执行,然后根据查询中提供的查询运算符(`should`、`must` 等)合并结果。 + - [`post_filter` 参数](#post-filter-parameter):这种方法先对完整数据集运行 [ANN](/search-plugins/knn/approximate-knn) 搜索,然后对 k-NN 结果应用过滤器。 + +- [评分脚本过滤器](#scoring-script-filter):这种方法先对文档集进行预过滤,然后对过滤后的子集运行精确 k-NN 搜索。它的延迟可能较高,并且在过滤后的子集较大时无法扩展。 + +下表总结了上述过滤用例。 + +过滤器 | 何时应用过滤器 | 搜索类型 | 支持的引擎和方法 | `filter` 子句的放置位置 +:--- | :--- | :--- | :--- +高效 k-NN 过滤 | 搜索期间(预过滤与后过滤的混合) | 近似 | - `lucene`(`hnsw`)
- `faiss`(`hnsw`、`ivf`) | 在 k-NN 查询子句内部。 +布尔过滤器 | 搜索之后(后过滤) | 近似 | - `lucene`
- `nmslib`
- `faiss` | 在 k-NN 查询子句外部。必须是叶子句。 +`post_filter` 参数 | 搜索之后(后过滤) | 近似 | - `lucene`
- `nmslib`
- `faiss` | 在 k-NN 查询子句外部。 +评分脚本过滤器 | 搜索之前(预过滤) | 精确 | 不适用 | 在 script score 查询子句内部。 + +## 过滤搜索优化 + +根据你的数据集和用例,你可能更关注最大化召回率或最小化延迟。下表针对各种 k-NN 搜索配置,给出了为获得更高召回率或更低延迟而应使用的过滤方法。表的前三列列出了几个 k-NN 搜索配置示例。一个搜索配置包括: + +- 索引中的文档数量,其中一个 OpenSearch 文档对应一个 k-NN 向量。 +- 过滤后结果中剩余文档的百分比。该值取决于你在查询中提供的过滤器的限制程度。表中限制最强的过滤器返回索引中 2.5% 的文档,而限制最弱的过滤器返回 80% 的文档。 +- 期望返回的结果数量(k)。 + +估算出索引中的文档数量、过滤器的限制程度以及期望的最近邻数量之后,可以使用下表选择针对召回率或延迟进行优化的过滤方法。 + +| 索引中的文档数量 | 过滤器返回的文档百分比 | k | 获得更高召回率应使用的过滤方法 | 获得更低延迟应使用的过滤方法 | +| :-- | :-- | :-- | :-- | :-- | +| 10M | 2.5 | 100 | 高效 k-NN 过滤/评分脚本 | 评分脚本 | +| 10M | 38 | 100 | 高效 k-NN 过滤 | 高效 k-NN 过滤 | +| 10M | 80 | 100 | 高效 k-NN 过滤 | 高效 k-NN 过滤 | +| 1M | 2.5 | 100 | 高效 k-NN 过滤/评分脚本 | 评分脚本 | +| 1M | 38 | 100 | 高效 k-NN 过滤 | 高效 k-NN 过滤 | +| 1M | 80 | 100 | 高效 k-NN 过滤 | 高效 k-NN 过滤 | + +## 高效 k-NN 过滤 + +你可以使用 `lucene` 或 `faiss` 引擎执行高效 k-NN 过滤。 + +### Lucene k-NN 过滤器实现 + +k-NN 插件 2.2 版本开始支持使用 HNSW 图通过 Lucene 引擎运行 k-NN 搜索。从基于 Lucene 9.4 版本的 2.4 版本开始,你可以在 k-NN 搜索中使用 Lucene 过滤器。 + +当你为 k-NN 搜索指定 Lucene 过滤器时,Lucene 算法会决定是执行带预过滤的精确 k-NN 搜索,还是执行带改进后过滤的近似搜索。该算法使用以下变量: + +- N:索引中的文档数量。 +- P:应用过滤器后文档子集中的文档数量(P <= N)。 +- k:响应中返回的最大向量数。 + +以下流程图概述了 Lucene 算法。 + +![用于过滤的 Lucene 算法](/images/lucene-algorithm.png) + +有关 Lucene 过滤实现以及底层 `KnnVectorQuery` 的更多信息,请参阅 [Apache Lucene 文档](https://lucene.apache.org/core/9_2_0/core/org/apache/lucene/search/KnnVectorQuery.html)。 + +### 使用 Lucene k-NN 过滤器 + +假设有一个数据集,包含 12 个存放酒店信息的文档。下图按位置在 xy 坐标平面上显示了所有酒店。此外,评分在 8 到 10(含)之间的酒店用橙色点表示,提供停车场的酒店用绿色圆圈表示。搜索点用红色表示: + +![包含过滤条件的文档图](/images/knn-doc-set-for-filtering.png) + +在本示例中,你将创建一个索引,并搜索距离搜索位置最近、评分较高且提供停车场的三家酒店。 + +**第 1 步:创建新索引** + +在运行带过滤器的 k-NN 搜索之前,需要创建一个包含 `knn_vector` 字段的索引。对于该字段,需要在映射中将引擎指定为 `lucene`,并将 `method` 指定为 `hnsw`。 + +以下请求创建一个名为 `hotels-index` 的新索引,其中包含一个名为 `location` 的 `knn-filter` 字段: + +```json +PUT /hotels-index +{ + "settings": { + "index": { + "knn": true, + "knn.algo_param.ef_search": 100, + "number_of_shards": 1, + "number_of_replicas": 0 + } + }, + "mappings": { + "properties": { + "location": { + "type": "knn_vector", + "dimension": 2, + "method": { + "name": "hnsw", + "space_type": "l2", + "engine": "lucene", + "parameters": { + "ef_construction": 100, + "m": 16 + } + } + } + } + } +} +``` + +**第 2 步:向索引添加数据** + +接下来,向索引添加数据。 + +以下请求添加 12 个包含酒店位置、评分和停车场信息的文档: + +```json +POST /_bulk +{ "index": { "_index": "hotels-index", "_id": "1" } } +{ "location": [5.2, 4.4], "parking" : "true", "rating" : 5 } +{ "index": { "_index": "hotels-index", "_id": "2" } } +{ "location": [5.2, 3.9], "parking" : "false", "rating" : 4 } +{ "index": { "_index": "hotels-index", "_id": "3" } } +{ "location": [4.9, 3.4], "parking" : "true", "rating" : 9 } +{ "index": { "_index": "hotels-index", "_id": "4" } } +{ "location": [4.2, 4.6], "parking" : "false", "rating" : 6} +{ "index": { "_index": "hotels-index", "_id": "5" } } +{ "location": [3.3, 4.5], "parking" : "true", "rating" : 8 } +{ "index": { "_index": "hotels-index", "_id": "6" } } +{ "location": [6.4, 3.4], "parking" : "true", "rating" : 9 } +{ "index": { "_index": "hotels-index", "_id": "7" } } +{ "location": [4.2, 6.2], "parking" : "true", "rating" : 5 } +{ "index": { "_index": "hotels-index", "_id": "8" } } +{ "location": [2.4, 4.0], "parking" : "true", "rating" : 8 } +{ "index": { "_index": "hotels-index", "_id": "9" } } +{ "location": [1.4, 3.2], "parking" : "false", "rating" : 5 } +{ "index": { "_index": "hotels-index", "_id": "10" } } +{ "location": [7.0, 9.9], "parking" : "true", "rating" : 9 } +{ "index": { "_index": "hotels-index", "_id": "11" } } +{ "location": [3.0, 2.3], "parking" : "false", "rating" : 6 } +{ "index": { "_index": "hotels-index", "_id": "12" } } +{ "location": [5.0, 1.0], "parking" : "true", "rating" : 3 } +``` + +**第 3 步:使用过滤器搜索数据** + +现在可以创建带过滤器的 k-NN 搜索。在 k-NN 查询子句中,包含用于搜索最近邻的目标点、要返回的最近邻数量(`k`)以及包含限制条件的过滤器。根据你希望过滤器达到的限制程度,可以在单个请求中添加多个查询子句。 + +以下请求创建一个 k-NN 查询,搜索坐标 `[5, 4]` 附近评分在 8 到 10(含)之间且提供停车场的前三家酒店: + +```json +POST /hotels-index/_search +{ + "size": 3, + "query": { + "knn": { + "location": { + "vector": [ + 5, + 4 + ], + "k": 3, + "filter": { + "bool": { + "must": [ + { + "range": { + "rating": { + "gte": 8, + "lte": 10 + } + } + }, + { + "term": { + "parking": "true" + } + } + ] + } + } + } + } + } +} +``` + +响应返回距离搜索点最近且满足过滤条件的三家酒店: + +```json +{ + "took" : 47, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 3, + "relation" : "eq" + }, + "max_score" : 0.72992706, + "hits" : [ + { + "_index" : "hotels-index", + "_id" : "3", + "_score" : 0.72992706, + "_source" : { + "location" : [ + 4.9, + 3.4 + ], + "parking" : "true", + "rating" : 9 + } + }, + { + "_index" : "hotels-index", + "_id" : "6", + "_score" : 0.3012048, + "_source" : { + "location" : [ + 6.4, + 3.4 + ], + "parking" : "true", + "rating" : 9 + } + }, + { + "_index" : "hotels-index", + "_id" : "5", + "_score" : 0.24154587, + "_source" : { + "location" : [ + 3.3, + 4.5 + ], + "parking" : "true", + "rating" : 8 + } + } + ] + } +} +``` + +有关构造过滤器的更多方式,请参阅[构造过滤器](#constructing-a-filter)。 + +### Faiss k-NN 过滤器实现 + +对于 k-NN 搜索,你可以将 `faiss` 过滤器与 HNSW 算法(k-NN 插件 2.9 及更高版本)或 IVF 算法(k-NN 插件 2.10 及更高版本)结合使用。 + +当你为 k-NN 搜索指定 Faiss 过滤器时,Faiss 算法会决定是执行带预过滤的精确 k-NN 搜索,还是执行带改进后过滤的近似搜索。该算法使用以下变量: + +- N:索引中的文档数量。 +- P:应用过滤器后文档子集中的文档数量(P <= N)。 +- k:响应中返回的最大向量数。 +- R:执行过滤后的近似最近邻搜索之后返回的结果数量。 +- FT(filtered threshold,过滤阈值):在 [`knn.advanced.filtered_exact_search_threshold` 设置](/search-plugins/knn/settings)中定义的索引级阈值,用于指定何时切换到精确搜索。 +- MDC(max distance computations,最大距离计算次数):未设置 `FT`(过滤阈值)时,精确搜索中允许的最大距离计算次数。该值无法更改。 + +以下流程图概述了 Faiss 算法。 + +![用于过滤的 Faiss 算法](/images/faiss-algorithm.jpg) + +### 使用 Faiss 高效过滤器 + +假设有一个索引,包含某个电子商务应用中各种衬衫的信息。你希望找到与你已有的衬衫相似且评分最高的衬衫,但希望按衬衫尺码限制结果。 + +在本示例中,你将创建一个索引,并搜索与你提供的衬衫相似的衬衫。 + +**第 1 步:创建新索引** + +在运行带过滤器的 k-NN 搜索之前,需要创建一个包含 `knn_vector` 字段的索引。对于该字段,需要在映射中指定 `faiss`,并将 `method` 指定为 `hnsw`。 + +以下请求创建一个包含衬衫向量表示的索引: + +```json +PUT /products-shirts +{ + "settings": { + "index": { + "knn": true + } + }, + "mappings": { + "properties": { + "item_vector": { + "type": "knn_vector", + "dimension": 3, + "method": { + "name": "hnsw", + "space_type": "l2", + "engine": "faiss" + } + } + } + } +} +``` + +**第 2 步:向索引添加数据** + +接下来,向索引添加数据。 + +以下请求添加 12 个包含衬衫信息的文档,包括其向量表示、尺码和评分: + +```json +POST /_bulk?refresh +{ "index": { "_index": "products-shirts", "_id": "1" } } +{ "item_vector": [5.2, 4.4, 8.4], "size" : "large", "rating" : 5 } +{ "index": { "_index": "products-shirts", "_id": "2" } } +{ "item_vector": [5.2, 3.9, 2.9], "size" : "small", "rating" : 4 } +{ "index": { "_index": "products-shirts", "_id": "3" } } +{ "item_vector": [4.9, 3.4, 2.2], "size" : "xlarge", "rating" : 9 } +{ "index": { "_index": "products-shirts", "_id": "4" } } +{ "item_vector": [4.2, 4.6, 5.5], "size" : "large", "rating" : 6} +{ "index": { "_index": "products-shirts", "_id": "5" } } +{ "item_vector": [3.3, 4.5, 8.8], "size" : "medium", "rating" : 8 } +{ "index": { "_index": "products-shirts", "_id": "6" } } +{ "item_vector": [6.4, 3.4, 6.6], "size" : "small", "rating" : 9 } +{ "index": { "_index": "products-shirts", "_id": "7" } } +{ "item_vector": [4.2, 6.2, 4.6], "size" : "small", "rating" : 5 } +{ "index": { "_index": "products-shirts", "_id": "8" } } +{ "item_vector": [2.4, 4.0, 3.0], "size" : "small", "rating" : 8 } +{ "index": { "_index": "products-shirts", "_id": "9" } } +{ "item_vector": [1.4, 3.2, 9.0], "size" : "small", "rating" : 5 } +{ "index": { "_index": "products-shirts", "_id": "10" } } +{ "item_vector": [7.0, 9.9, 9.0], "size" : "xlarge", "rating" : 9 } +{ "index": { "_index": "products-shirts", "_id": "11" } } +{ "item_vector": [3.0, 2.3, 2.0], "size" : "large", "rating" : 6 } +{ "index": { "_index": "products-shirts", "_id": "12" } } +{ "item_vector": [5.0, 1.0, 4.0], "size" : "large", "rating" : 3 } + +``` + +**第 3 步:使用过滤器搜索数据** + +现在可以创建带过滤器的 k-NN 搜索。在 k-NN 查询子句中,包含用于搜索相似衬衫的衬衫向量表示、要返回的最近邻数量(`k`),以及按尺码和评分进行过滤的过滤器。 + +以下请求搜索评分在 7 到 10(含)之间的 small 尺码衬衫: + +```json +POST /products-shirts/_search +{ + "size": 2, + "query": { + "knn": { + "item_vector": { + "vector": [ + 2, 4, 3 + ], + "k": 10, + "filter": { + "bool": { + "must": [ + { + "range": { + "rating": { + "gte": 7, + "lte": 10 + } + } + }, + { + "term": { + "size": "small" + } + } + ] + } + } + } + } + } +} +``` + +响应返回两个匹配的文档: + +```json +{ + "took": 2, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.8620689, + "hits": [ + { + "_index": "products-shirts", + "_id": "8", + "_score": 0.8620689, + "_source": { + "item_vector": [ + 2.4, + 4, + 3 + ], + "size": "small", + "rating": 8 + } + }, + { + "_index": "products-shirts", + "_id": "6", + "_score": 0.029691212, + "_source": { + "item_vector": [ + 6.4, + 3.4, + 6.6 + ], + "size": "small", + "rating": 9 + } + } + ] + } +} +``` + +有关构造过滤器的更多方式,请参阅[构造过滤器](#constructing-a-filter)。 + +### 构造过滤器 + +对于同一条件,可以通过多种方式构造过滤器。例如,你可以使用以下结构创建一个返回提供停车场的酒店的过滤器: + +- 在 `should` 子句中使用 `term` 查询子句 +- 在 `should` 子句中使用 `wildcard` 查询子句 +- 在 `should` 子句中使用 `regexp` 查询子句 +- 使用 `must_not` 子句排除 `parking` 设置为 `false` 的酒店。 + +以下请求演示了搜索提供停车场的酒店的这四种不同方式: + +```json +POST /hotels-index/_search +{ + "size": 3, + "query": { + "knn": { + "location": { + "vector": [ 5.0, 4.0 ], + "k": 3, + "filter": { + "bool": { + "must": { + "range": { + "rating": { + "gte": 1, + "lte": 6 + } + } + }, + "should": [ + { + "term": { + "parking": "true" + } + }, + { + "wildcard": { + "parking": { + "value": "t*e" + } + } + }, + { + "regexp": { + "parking": "[a-zA-Z]rue" + } + } + ], + "must_not": [ + { + "term": { + "parking": "false" + } + } + ], + "minimum_should_match": 1 + } + } + } + } + } +} +``` + +## 后过滤 + +你可以使用布尔过滤器或通过提供 `post_filter` 参数来实现后过滤。 + +### 结合 ANN 搜索的布尔过滤器 + +布尔过滤器由一个包含 k-NN 查询和过滤器的布尔查询组成。例如,以下查询搜索距离指定 `location` 最近的酒店,然后对结果进行过滤,返回评分在 8 到 10(含)之间且提供停车场的酒店: + +```json +POST /hotels-index/_search +{ + "size": 3, + "query": { + "bool": { + "filter": { + "bool": { + "must": [ + { + "range": { + "rating": { + "gte": 8, + "lte": 10 + } + } + }, + { + "term": { + "parking": "true" + } + } + ] + } + }, + "must": [ + { + "knn": { + "location": { + "vector": [ + 5, + 4 + ], + "k": 20 + } + } + } + ] + } + } +} +``` + +响应中包含匹配酒店的文档: + +```json +{ + "took" : 95, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 5, + "relation" : "eq" + }, + "max_score" : 0.72992706, + "hits" : [ + { + "_index" : "hotels-index", + "_id" : "3", + "_score" : 0.72992706, + "_source" : { + "location" : [ + 4.9, + 3.4 + ], + "parking" : "true", + "rating" : 9 + } + }, + { + "_index" : "hotels-index", + "_id" : "6", + "_score" : 0.3012048, + "_source" : { + "location" : [ + 6.4, + 3.4 + ], + "parking" : "true", + "rating" : 9 + } + }, + { + "_index" : "hotels-index", + "_id" : "5", + "_score" : 0.24154587, + "_source" : { + "location" : [ + 3.3, + 4.5 + ], + "parking" : "true", + "rating" : 8 + } + } + ] + } +} +``` + +### post-filter 参数 + +如果将 `knn` 查询与过滤器或其他子句(例如 `bool`、`must`、`match`)一起使用,返回的结果可能少于 `k` 个。在本示例中,`post_filter` 将结果数量从 2 个减少到 1 个: + +```json +GET my-knn-index-1/_search +{ + "size": 2, + "query": { + "knn": { + "my_vector2": { + "vector": [2, 3, 5, 6], + "k": 2 + } + } + }, + "post_filter": { + "range": { + "price": { + "gte": 5, + "lte": 10 + } + } + } +} +``` + +## 评分脚本过滤器 + +评分脚本过滤器先过滤文档,然后对结果使用暴力精确 k-NN 搜索。例如,以下查询先搜索评分在 8 到 10(含)之间且提供停车场的酒店,然后执行 k-NN 搜索,返回距离指定 `location` 最近的 3 家酒店: + +```json +POST /hotels-index/_search +{ + "size": 3, + "query": { + "script_score": { + "query": { + "bool": { + "filter": { + "bool": { + "must": [ + { + "range": { + "rating": { + "gte": 8, + "lte": 10 + } + } + }, + { + "term": { + "parking": "true" + } + } + ] + } + } + } + }, + "script": { + "source": "knn_score", + "lang": "knn", + "params": { + "field": "location", + "query_value": [ + 5.0, + 4.0 + ], + "space_type": "l2" + } + } + } + } +} +``` diff --git a/i18n/zh/search-plugins/knn/index.md b/i18n/zh/search-plugins/knn/index.md new file mode 100644 index 00000000..27a99253 --- /dev/null +++ b/i18n/zh/search-plugins/knn/index.md @@ -0,0 +1,37 @@ +--- +title: k-NN 搜索 +--- + +# k-NN 搜索 + +k-NN 是 *k 最近邻(k-nearest neighbors)* 的缩写。借助 k-NN 插件,用户可以在由向量(Vector)组成的索引中,搜索与查询点距离最近的 k 个邻居。为了确定这些邻居,你可以指定用于度量点间距离的空间(即距离函数)。 + +典型用例包括推荐(例如音乐应用中的「你可能还喜欢的其他歌曲」功能)、图像识别和欺诈检测。有关 k-NN 搜索的更多背景信息,请参阅 [Wikipedia](https://en.wikipedia.org/wiki/Nearest_neighbor_search)。 + +该插件支持三种从向量索引中获取 k 最近邻的方法: + +1. **近似 k-NN(Approximate k-NN)** + + 第一种方法采用近似最近邻的思路——使用若干算法之一,返回与查询向量近似的 k 个最近邻。通常,这些算法会牺牲索引速度和搜索精度,以换取更低的延迟、更小的内存占用和更好的搜索可扩展性等性能优势。要详细了解这些算法,请参阅 [*nmslib*](https://github.com/nmslib/nmslib/blob/master/manual/README.md) 和 [*faiss*](https://github.com/facebookresearch/faiss/wiki) 的文档。 + + 对于需要低延迟、且数据量很大的索引(即包含数十万甚至更多向量)上的搜索,近似 k-NN 是最佳选择。如果你希望在 k-NN 搜索之前先对索引应用过滤器,从而大幅减少需要搜索的向量数量,则不应使用近似 k-NN。在这种情况下,应使用脚本评分方法或 Painless 扩展。 + + 有关此方法的更多详细信息(包括使用哪种引擎的建议),请参阅[近似 k-NN 搜索](/search-plugins/knn/approximate-knn)。 + +2. **Script Score k-NN** + + 第二种方法扩展了 OpenSearch 的脚本评分功能,可在 "knn_vector" 字段或可表示二进制对象的字段上执行暴力(brute force)精确 k-NN 搜索。使用这种方法,你可以只在索引中的一部分向量上运行 k-NN 搜索(有时称为预过滤搜索)。 + + 当搜索的文档集合较小,或需要预过滤时,请使用这种方法。在大型索引上使用这种方法可能会导致较高的延迟。 + + 有关此方法的更多详细信息,请参阅[使用评分脚本的精确 k-NN](/search-plugins/knn/knn-score-script)。 + +3. **Painless 扩展** + + 第三种方法将距离函数作为 Painless 扩展提供,你可以在更复杂的组合中使用它们。与 k-NN Script Score 类似,你可以使用这种方法在索引上执行暴力精确 k-NN 搜索,同样支持预过滤。 + + 与 k-NN Script Score 相比,这种方法的查询性能略慢。如果你的用例需要对最终评分进行更多自定义,则应优先使用这种方法,而不是 Script Score k-NN。 + + 有关此方法的更多详细信息,请参阅 [Painless 脚本函数](/search-plugins/knn/painless-functions)。 + +总体而言,对于较大的数据集,通常应选择近似最近邻方法,因为它的可扩展性要好得多。对于可能需要应用过滤器的较小数据集,应选择自定义评分方法。如果你的用例更复杂,需要将距离函数作为评分方法的一部分,则应使用 Painless 脚本方法。 diff --git a/i18n/zh/search-plugins/knn/jni-libraries.md b/i18n/zh/search-plugins/knn/jni-libraries.md new file mode 100644 index 00000000..53837889 --- /dev/null +++ b/i18n/zh/search-plugins/knn/jni-libraries.md @@ -0,0 +1,17 @@ +--- +title: JNI 库 +--- + +# JNI 库 + +为了将 [nmslib](https://github.com/nmslib/nmslib/) 和 [faiss](https://github.com/facebookresearch/faiss/) 的近似 k-NN 功能(使用 C++ 实现)集成到 k-NN 插件(使用 Java 实现)中,我们创建了一个 Java 本地接口(Java Native Interface,JNI),使 k-NN 插件能够调用本地库。该接口包括三个库:`libopensearchknn_nmslib`,即与 nmslib 交互的 JNI 库;`libopensearchknn_faiss`,即与 faiss 交互的 JNI 库;以及 `libopensearchknn_common`,即包含各本地库之间共享的通用功能的库。 + +::: info 注意 +Lucene 库不是通过本地库实现的。 +::: + +`libopensearchknn_faiss` 和 `libopensearchknn_nmslib` 这两个库采用延迟加载,在插件中首次调用时才会加载。这意味着,如果你只打算使用其中一个库,插件永远不会加载另一个库。 + +要从源代码构建这些库,请参阅 [DEVELOPER_GUIDE](https://github.com/opensearch-project/k-NN/blob/main/DEVELOPER_GUIDE.md)。 + +有关 JNI 的更多信息,请参阅 Wikipedia 上的 [Java Native Interface](https://en.wikipedia.org/wiki/Java_Native_Interface)。 diff --git a/i18n/zh/search-plugins/knn/knn-index.md b/i18n/zh/search-plugins/knn/knn-index.md new file mode 100644 index 00000000..0414d660 --- /dev/null +++ b/i18n/zh/search-plugins/knn/knn-index.md @@ -0,0 +1,272 @@ +--- +title: k-NN 索引 +--- + +# k-NN 索引 + +k-NN 插件引入了一种自定义数据类型(data type)`knn_vector`,用户可以借助它将 k-NN 向量摄取到 OpenSearch 索引中,并执行各种 k-NN 搜索。`knn_vector` 字段高度可配置,能够满足多种不同的 k-NN 工作负载。有关更多信息,请参阅 [k-NN 向量](/field-types/supported-field-types/knn-vector)。 + +## Lucene 字节向量 + +从 k-NN 插件 2.9 版本开始,你可以在 `lucene` 引擎中使用 `byte` 向量,以减少所需的存储空间。有关更多信息,请参阅 [Lucene 字节向量](/field-types/supported-field-types/knn-vector#lucene-byte-vector)。 + +## 方法定义 + +方法定义是指你要使用的近似 k-NN 算法的底层配置。方法定义可用于创建 `knn_vector` 字段(当该方法不需要训练时),也可用于[在训练期间创建模型](/search-plugins/knn/api#train-model),之后再使用该模型[创建 `knn_vector` 字段](/search-plugins/knn/approximate-knn#building-a-k-nn-index-from-a-model)。 + +方法定义始终包含方法名称、该方法所针对的 space_type、要使用的引擎 +(库),以及一个参数映射。 + +映射参数 | 必需 | 默认值 | 可更新 | 描述 +:--- | :--- | :--- | :--- | :--- +`name` | true | n/a | false | 最近邻方法的标识符。 +`space_type` | false | l2 | false | 用于计算向量之间距离的向量空间。 +`engine` | false | nmslib | false | 用于索引和搜索的近似 k-NN 库。可用的库有 faiss、nmslib 和 Lucene。 +`parameters` | false | null | false | 最近邻方法所使用的参数。 + +### 支持的 nmslib 方法 + +方法名称 | 需要训练 | 支持的空间 | 描述 +:--- | :--- | :--- | :--- +`hnsw` | false | l2, innerproduct, cosinesimil, l1, linf | 一种用于近似 k-NN 搜索的分层邻近图方法。有关该算法的更多详细信息,请参阅这篇[摘要](https://arxiv.org/abs/1603.09320)。 + +#### HNSW 参数 + +参数名称 | 必需 | 默认值 | 可更新 | 描述 +:--- | :--- | :--- | :--- | :--- +`ef_construction` | false | 100 | false | 创建 k-NN 图时使用的动态列表的大小。值越大,图越精确,但索引速度越慢。 +`m` | false | 16 | false | 插件为每个新元素创建的双向链接数。增大或减小此值会对内存消耗产生很大影响。请将此值保持在 2 到 100 之间。 + +::: info 注意 +对于 nmslib,*ef_search* 在[索引设置](#index-settings)中设置。 +::: + +::: info 注意 +在 OpenSearch 2.11 或更早版本中创建的索引仍会使用旧的 `ef_construction` 值(`512`)。 +::: + +### 支持的 faiss 方法 + +方法名称 | 需要训练 | 支持的空间 | 描述 +:--- | :--- | :--- | :--- +`hnsw` | false | l2, innerproduct | 一种用于近似 k-NN 搜索的分层邻近图方法。 +`ivf` | true | l2, innerproduct | 一种分桶方法:根据聚类将向量分配到不同的桶中,搜索时只搜索其中一部分桶。 + +::: info 注意 +对于 hnsw,使用 PQ 时不能使用 "innerproduct"。 +::: + +#### HNSW 参数 {#hnsw-parameters-1} + +参数名称 | 必需 | 默认值 | 可更新 | 描述 +:--- | :--- | :--- | :--- | :--- +`ef_search` | false | 100 | false | k-NN 搜索时使用的动态列表的大小。值越大,搜索越精确,但速度越慢。 +`ef_construction` | false | 100 | false | 创建 k-NN 图时使用的动态列表的大小。值越大,图越精确,但索引速度越慢。 +`m` | false | 16 | false | 插件为每个新元素创建的双向链接数。增大或减小此值会对内存消耗产生很大影响。请将此值保持在 2 到 100 之间。 +`encoder` | false | flat | false | 用于对向量进行编码的编码器定义。编码器可以减少索引的内存占用,但会牺牲搜索精度。 + +::: info 注意 +在 OpenSearch 2.11 或更早版本中创建的索引仍会使用旧的 `ef_construction` 和 `ef_search` 值(`512`)。 +::: + +#### IVF 参数 + +参数名称 | 必需 | 默认值 | 可更新 | 描述 +:--- | :--- | :--- | :--- | :--- +`nlist` | false | 4 | false | 将向量划分到的桶的数量。值越大,搜索可能越精确,但会增加内存占用和训练延迟。有关如何选择合适的值的更多信息,请参阅 [Guidelines to choose an index](https://github.com/facebookresearch/faiss/wiki/Guidelines-to-choose-an-index)。 +`nprobes` | false | 1 | false | 查询时要搜索的桶的数量。值越大,搜索越精确,但速度越慢。 +`encoder` | false | flat | false | 用于对向量进行编码的编码器定义。编码器可以减少索引的内存占用,但会牺牲搜索精度。 + +有关设置这些参数的更多信息,请参阅 [Faiss 文档](https://github.com/facebookresearch/faiss/wiki/Faiss-indexes)。 + +#### IVF 训练要求 + +IVF 算法需要一个训练步骤。要创建使用 IVF 的索引,你需要使用 +[Train API](/search-plugins/knn/api#train-model) 训练一个模型,并传入 IVF 方法定义。IVF 要求训练数据点的数量至少为 `nlist` +个,但[建议使用更多](https://github.com/facebookresearch/faiss/wiki/Guidelines-to-choose-an-index#how-big-is-the-dataset)。 +训练数据既可以是将要摄取的相同数据,也可以是一个单独的数据集。 + +### 支持的 Lucene 方法 + +方法名称 | 需要训练 | 支持的空间 | 描述 +:--- | :--- | :--- | :--- +`hnsw` | false | l2, cosinesimil | 一种用于近似 k-NN 搜索的分层邻近图方法。 + +#### HNSW 参数 {#hnsw-parameters-2} + +参数名称 | 必需 | 默认值 | 可更新 | 描述 +:--- | :--- | :--- | :--- | :--- +`ef_construction` | false | 100 | false | 创建 k-NN 图时使用的动态列表的大小。值越大,图越精确,但索引速度越慢。
Lucene 引擎使用其专有术语 "beam_width" 来描述这一功能,它与 "ef_construction" 直接对应。为了在整个 OpenSearch 文档中保持一致,我们对此参数保留 "ef_construction" 这一术语。 +`m` | false | 16 | false | 插件为每个新元素创建的双向链接数。增大或减小此值会对内存消耗产生很大影响。请将此值保持在 2 到 100 之间。
Lucene 引擎使用其专有术语 "max_connections" 来描述这一功能,它与 "m" 直接对应。为了在整个 OpenSearch 文档中保持一致,我们保留 "m" 这一术语来命名此参数。 + +::: info 注意 +Lucene 的 HNSW 实现会忽略 `ef_search`,并将其动态设置为搜索请求中 "k" 的值。因此,使用 Lucene 引擎时无需设置 `ef_search`。 +::: + +::: info 注意 +在 OpenSearch 2.11 或更早版本中创建的索引仍会使用旧的 `ef_construction` 值(`512`)。 +::: + +```json +{ + "type": "knn_vector", + "dimension": 100, + "method": { + "name":"hnsw", + "engine":"lucene", + "space_type": "l2", + "parameters":{ + "m":2048, + "ef_construction": 245 + } + } +} +``` + +### 支持的 faiss 编码器 + +你可以使用编码器来减少 k-NN 索引的内存占用,但会牺牲搜索精度。faiss 提供了 +多种编码器类型,但该插件目前只支持 *flat* 和 *pq* 编码。 + +以下示例方法定义指定了 `hnsw` 方法和 `pq` 编码器: + +```json +"method": { + "name":"hnsw", + "engine":"faiss", + "space_type": "l2", + "parameters":{ + "encoder":{ + "name":"pq", + "parameters":{ + "code_size": 8, + "m": 8 + } + } + } +} +``` + +::: warning 重要 +在 OpenSearch 2.10 及更高版本中,`hnsw` 方法支持 `pq` 编码器。与 `hnsw` 方法一起使用的 `pq` 编码器,其 `code_size` 参数必须为 **8**。 +::: + +编码器名称 | 需要训练 | 描述 +:--- | :--- | :--- +`flat` | false | 将向量编码为浮点数组。这种编码不会减少内存占用。 +`pq` | true | 即 *乘积量化(product quantization)* 的缩写,是一种有损压缩技术,它通过聚类将向量编码为固定字节数,目标是尽量减少 k-NN 搜索精度的下降。从整体上看,向量被拆分为 `m` 个子向量,然后每个子向量用一个 `code_size` 编码表示,该编码来自训练期间生成的码本。有关乘积量化的更多信息,请参阅[这篇博客文章](https://medium.com/dotstar/understanding-faiss-part-2-79d90b1e5388)。 + +#### 示例 + +以下示例使用 `ivf` 方法,未指定编码器(默认情况下,OpenSearch 使用 `flat` 编码器): + +```json +"method": { + "name":"ivf", + "engine":"faiss", + "space_type": "l2", + "parameters":{ + "nlist": 4, + "nprobes": 2 + } +} +``` + +以下示例使用 `ivf` 方法和 `pq` 编码器: + +```json +"method": { + "name":"ivf", + "engine":"faiss", + "space_type": "l2", + "parameters":{ + "encoder":{ + "name":"pq", + "parameters":{ + "code_size": 8, + "m": 8 + } + } + } +} +``` + +以下示例使用 `hnsw` 方法,未指定编码器(默认情况下,OpenSearch 使用 `flat` 编码器): + +```json +"method": { + "name":"hnsw", + "engine":"faiss", + "space_type": "l2", + "parameters":{ + "ef_construction": 256, + "m": 8 + } +} +``` + +#### PQ 参数 + +参数名称 | 必需 | 默认值 | 可更新 | 描述 +:--- | :--- | :--- | :--- | :--- +`m` | false | 1 | false | 决定将向量拆分为多少个子向量。各子向量相互独立地进行编码。向量的维度必须能被 `m` 整除。最大值为 1,024。 +`code_size` | false | 8 | false | 决定将子向量编码为多少位。最大值为 8。对于 IVF,此值必须小于或等于 8。对于 HNSW,此值只能为 8。 + +### 选择合适的方法 + +构建 `knn_vector` 字段时有很多选项可供选择。要确定应选择的方法和参数,首先应了解你的工作负载有哪些要求,以及你愿意做出哪些权衡。需要考虑的因素有:(1) 查询延迟,(2) 查询质量,(3) 内存限制,(4) 索引延迟。 + +如果不需要考虑内存,HNSW 在查询延迟与查询质量之间的权衡非常出色。 + +如果你希望比 HNSW 占用更少的内存、索引更快,同时保持相近的查询质量,则应评估 IVF。 + +如果需要考虑内存,可以考虑为 HNSW 或 IVF 索引添加 PQ 编码器。由于 PQ 是有损编码,查询质量会有所下降。 + +### 内存估算 + +在典型的 OpenSearch 集群中,一部分 RAM 会预留给 JVM 堆。k-NN 插件会将本地库索引 +分配到剩余 RAM 中的一部分。这部分的大小由 +`circuit_breaker_limit` 集群设置决定。默认情况下,该限制为 50%。 + +::: info 注意 +有一个副本会使向量总数翻倍。 +::: + +#### HNSW 内存估算 + +HNSW 所需的内存估计为 `1.1 * (4 * dimension + 8 * M)` 字节/向量。 + +例如,假设你有一百万个向量,维度为 256,M 为 16。所需内存可以估算如下: + +``` +1.1 * (4 * 256 + 8 * 16) * 1,000,000 ~= 1.267 GB +``` + +#### IVF 内存估算 + +IVF 所需的内存估计为 `1.1 * (((4 * dimension) * num_vectors) + (4 * nlist * d))` 字节。 + +例如,假设你有一百万个向量,维度为 256,nlist 为 128。所需内存可以估算如下: + +``` +1.1 * (((4 * 256) * 1,000,000) + (4 * 128 * 256)) ~= 1.126 GB + +``` + +## 索引设置 + +此外,k-NN 插件还引入了若干索引设置,也可用于配置 k-NN 结构。 + +目前,设置中定义的若干参数正处于弃用过程中。这些参数应在映射中设置,而不是在索引设置中设置。在映射中设置的参数会覆盖在索引设置中设置的参数。在映射中设置参数,可以让一个索引拥有多个参数各不相同的 `knn_vector` 字段。 + +设置 | 默认值 | 可更新 | 描述 +:--- | :--- | :--- | :--- +`index.knn` | false | false | 是否为 `knn_vector` 字段构建本地库索引。如果设置为 false,`knn_vector` 字段将存储在 doc values 中,但近似 k-NN 搜索功能将被禁用。 +`index.knn.algo_param.ef_search` | 100 | true | k-NN 搜索时使用的动态列表的大小。值越大,搜索越精确,但速度越慢。仅适用于 NMSLIB。 +`index.knn.algo_param.ef_construction` | 100 | false | 已在 1.0.0 中弃用。请改用[映射参数](https://opensearch.org/docs/latest/search-plugins/knn/knn-index/#method-definitions)来设置此值。 +`index.knn.algo_param.m` | 16 | false | 已在 1.0.0 中弃用。请改用[映射参数](https://opensearch.org/docs/latest/search-plugins/knn/knn-index/#method-definitions)来设置此值。 +`index.knn.space_type` | l2 | false | 已在 1.0.0 中弃用。请改用[映射参数](https://opensearch.org/docs/latest/search-plugins/knn/knn-index/#method-definitions)来设置此值。 + +::: info 注意 +在 OpenSearch 2.11 或更早版本中创建的索引仍会使用旧的 `ef_construction` 和 `ef_search` 值(`512`)。 +::: diff --git a/i18n/zh/search-plugins/knn/knn-score-script.md b/i18n/zh/search-plugins/knn/knn-score-script.md new file mode 100644 index 00000000..53973537 --- /dev/null +++ b/i18n/zh/search-plugins/knn/knn-score-script.md @@ -0,0 +1,322 @@ +--- +title: 使用评分脚本的精确 k-NN +--- + +# 使用评分脚本的精确 k-NN + +k-NN 插件实现了 OpenSearch 的评分脚本插件,你可以用它找出与给定查询点精确的 k 个最近邻。使用 k-NN 评分脚本,你可以在执行最近邻搜索之前先对索引应用过滤器。这对于索引内容可能因其他条件而变化的动态搜索场景非常有用。 + +由于评分脚本方法执行的是暴力搜索,它的可扩展性不如[近似方法](/search-plugins/knn/approximate-knn)。在某些情况下,最好考虑重构工作流或索引结构,以使用近似方法代替评分脚本方法。 + +## 针对向量使用评分脚本入门 + +与近似最近邻搜索类似,要在一组向量(Vector)上使用评分脚本,必须先创建一个包含一个或多个 `knn_vector` 字段的索引。 + +如果你只打算使用评分脚本方法(而不使用近似方法),可以将 `index.knn` 设置为 `false`,并且不设置 `index.knn.space_type`。你可以在搜索时选择空间类型。有关 k-NN 评分脚本支持的空间,请参阅[空间](#spaces)。 + +以下示例创建一个包含两个 `knn_vector` 字段的索引: + +```json +PUT my-knn-index-1 +{ + "mappings": { + "properties": { + "my_vector1": { + "type": "knn_vector", + "dimension": 2 + }, + "my_vector2": { + "type": "knn_vector", + "dimension": 4 + } + } + } +} +``` + +::: tip 提示 +如果你*只*想使用评分脚本,可以省略 `"index.knn": true`。这种方式的好处是索引速度更快、内存占用更低,但你将无法在该索引上执行标准的 k-NN 查询。 +::: + +创建索引后,可以向其中添加一些数据: + +```json +POST _bulk +{ "index": { "_index": "my-knn-index-1", "_id": "1" } } +{ "my_vector1": [1.5, 2.5], "price": 12.2 } +{ "index": { "_index": "my-knn-index-1", "_id": "2" } } +{ "my_vector1": [2.5, 3.5], "price": 7.1 } +{ "index": { "_index": "my-knn-index-1", "_id": "3" } } +{ "my_vector1": [3.5, 4.5], "price": 12.9 } +{ "index": { "_index": "my-knn-index-1", "_id": "4" } } +{ "my_vector1": [5.5, 6.5], "price": 1.2 } +{ "index": { "_index": "my-knn-index-1", "_id": "5" } } +{ "my_vector1": [4.5, 5.5], "price": 3.7 } +{ "index": { "_index": "my-knn-index-1", "_id": "6" } } +{ "my_vector2": [1.5, 5.5, 4.5, 6.4], "price": 10.3 } +{ "index": { "_index": "my-knn-index-1", "_id": "7" } } +{ "my_vector2": [2.5, 3.5, 5.6, 6.7], "price": 5.5 } +{ "index": { "_index": "my-knn-index-1", "_id": "8" } } +{ "my_vector2": [4.5, 5.5, 6.7, 3.7], "price": 4.4 } +{ "index": { "_index": "my-knn-index-1", "_id": "9" } } +{ "my_vector2": [1.5, 5.5, 4.5, 6.4], "price": 8.9 } + +``` + +最后,可以使用 `knn` 脚本对数据执行精确最近邻搜索: +```json +GET my-knn-index-1/_search +{ + "size": 4, + "query": { + "script_score": { + "query": { + "match_all": {} + }, + "script": { + "source": "knn_score", + "lang": "knn", + "params": { + "field": "my_vector2", + "query_value": [2.0, 3.0, 5.0, 6.0], + "space_type": "cosinesimil" + } + } + } + } +} +``` + +所有参数都是必需的。 + +- `lang` 是脚本类型。该值通常为 `painless`,但这里必须指定为 `knn`。 +- `source` 是脚本的名称,即 `knn_score`。 + + 该脚本是 k-NN 插件的一部分,在标准的 `_scripts` 路径下不可用。向 `_cluster/state/metadata` 发送 GET 请求也不会返回它。 + +- `field` 是包含向量数据的字段。 +- `query_value` 是你要查找其最近邻的点。对于欧氏空间和余弦相似度空间,该值必须是一个浮点数组,且与字段映射中设置的维度一致。对于汉明位距离(Hamming bit distance),该值可以是有符号 long 类型,也可以是 base64 编码的字符串(分别对应 long 和 binary 字段类型)。 +- `space_type` 对应距离函数。请参阅[空间部分](#spaces)。 + +[近似方法中的后过滤示例](/search-plugins/knn/approximate-knn#using-approximate-k-nn-with-filters)展示了一个返回结果少于 `k` 个的搜索。如果你想避免这种情况,评分脚本方法实际上可以让你颠倒操作顺序。换句话说,你可以先过滤出要执行 k 最近邻搜索的文档集合。 + +以下示例展示了如何使用评分脚本方法对 k-NN 搜索进行预过滤。首先,创建索引: + +```json +PUT my-knn-index-2 +{ + "mappings": { + "properties": { + "my_vector": { + "type": "knn_vector", + "dimension": 2 + }, + "color": { + "type": "keyword" + } + } + } +} +``` + +然后添加一些文档: + +```json +POST _bulk +{ "index": { "_index": "my-knn-index-2", "_id": "1" } } +{ "my_vector": [1, 1], "color" : "RED" } +{ "index": { "_index": "my-knn-index-2", "_id": "2" } } +{ "my_vector": [2, 2], "color" : "RED" } +{ "index": { "_index": "my-knn-index-2", "_id": "3" } } +{ "my_vector": [3, 3], "color" : "RED" } +{ "index": { "_index": "my-knn-index-2", "_id": "4" } } +{ "my_vector": [10, 10], "color" : "BLUE" } +{ "index": { "_index": "my-knn-index-2", "_id": "5" } } +{ "my_vector": [20, 20], "color" : "BLUE" } +{ "index": { "_index": "my-knn-index-2", "_id": "6" } } +{ "my_vector": [30, 30], "color" : "BLUE" } + +``` + +最后,在确定最近邻之前,使用 `script_score` 查询对文档进行预过滤: + +```json +GET my-knn-index-2/_search +{ + "size": 2, + "query": { + "script_score": { + "query": { + "bool": { + "filter": { + "term": { + "color": "BLUE" + } + } + } + }, + "script": { + "lang": "knn", + "source": "knn_score", + "params": { + "field": "my_vector", + "query_value": [9.9, 9.9], + "space_type": "l2" + } + } + } + } +} +``` + +## 针对二进制数据使用评分脚本入门 +k-NN 评分脚本还允许你使用汉明距离空间,在二进制数据上运行 k-NN 搜索。 +要使用汉明距离,目标字段的字段类型必须是 `binary` 或 `long`。如果使用 `binary` 类型,数据必须是 base64 编码的字符串。 + +以下示例展示了如何对 `binary` 字段类型使用汉明距离空间: + +```json +PUT my-index +{ + "mappings": { + "properties": { + "my_binary": { + "type": "binary", + "doc_values": true + }, + "color": { + "type": "keyword" + } + } + } +} +``` + +然后添加一些文档: + +```json +POST _bulk +{ "index": { "_index": "my-index", "_id": "1" } } +{ "my_binary": "SGVsbG8gV29ybGQh", "color" : "RED" } +{ "index": { "_index": "my-index", "_id": "2" } } +{ "my_binary": "ay1OTiBjdXN0b20gc2NvcmluZyE=", "color" : "RED" } +{ "index": { "_index": "my-index", "_id": "3" } } +{ "my_binary": "V2VsY29tZSB0byBrLU5O", "color" : "RED" } +{ "index": { "_index": "my-index", "_id": "4" } } +{ "my_binary": "SSBob3BlIHRoaXMgaXMgaGVscGZ1bA==", "color" : "BLUE" } +{ "index": { "_index": "my-index", "_id": "5" } } +{ "my_binary": "QSBjb3VwbGUgbW9yZSBkb2NzLi4u", "color" : "BLUE" } +{ "index": { "_index": "my-index", "_id": "6" } } +{ "my_binary": "TGFzdCBvbmUh", "color" : "BLUE" } + +``` + +最后,在确定最近邻之前,使用 `script_score` 查询对文档进行预过滤: + +```json +GET my-index/_search +{ + "size": 2, + "query": { + "script_score": { + "query": { + "bool": { + "filter": { + "term": { + "color": "BLUE" + } + } + } + }, + "script": { + "lang": "knn", + "source": "knn_score", + "params": { + "field": "my_binary", + "query_value": "U29tZXRoaW5nIEltIGxvb2tpbmcgZm9y", + "space_type": "hammingbit" + } + } + } + } +} +``` + +同样,你也可以使用 `long` 字段对数据进行编码并运行搜索: + +```json +GET my-long-index/_search +{ + "size": 2, + "query": { + "script_score": { + "query": { + "bool": { + "filter": { + "term": { + "color": "BLUE" + } + } + } + }, + "script": { + "lang": "knn", + "source": "knn_score", + "params": { + "field": "my_long", + "query_value": 23, + "space_type": "hammingbit" + } + } + } + } +} +``` + +## 空间 + +空间对应用于度量两点之间距离的函数,以确定 k 个最近邻。从 k-NN 的角度来看,评分越低,表示结果越近、越好。这与 OpenSearch 的评分方式相反:在 OpenSearch 中,评分越高表示结果越好。下表说明了 OpenSearch 如何将空间转换为评分: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
spaceType距离函数 (d)OpenSearch 评分
l1\[ d(\mathbf{x}, \mathbf{y}) = \sum_{i=1}^n |x_i - y_i| \]\[ score = {1 \over 1 + d } \]
l2\[ d(\mathbf{x}, \mathbf{y}) = \sum_{i=1}^n (x_i - y_i)^2 \]\[ score = {1 \over 1 + d } \]
linf\[ d(\mathbf{x}, \mathbf{y}) = max(|x_i - y_i|) \]\[ score = {1 \over 1 + d } \]
cosinesimil\[ d(\mathbf{x}, \mathbf{y}) = 1 - cos { \theta } = 1 - {\mathbf{x} · \mathbf{y} \over \|\mathbf{x}\| · \|\mathbf{y}\|}\]\[ = 1 - + {\sum_{i=1}^n x_i y_i \over \sqrt{\sum_{i=1}^n x_i^2} · \sqrt{\sum_{i=1}^n y_i^2}}\] + 其中 \(\|\mathbf{x}\|\) 和 \(\|\mathbf{y}\|\) 分别表示向量 x 和 y 的范数。\[ score = 2 - d \]
innerproduct(Lucene 不支持)\[ d(\mathbf{x}, \mathbf{y}) = - {\mathbf{x} · \mathbf{y}} = - \sum_{i=1}^n x_i y_i \]\[ \text{If} d \ge 0, \] \[score = {1 \over 1 + d }\] \[\text{If} d < 0, score = −d + 1\]
hammingbit\[ d(\mathbf{x}, \mathbf{y}) = \text{countSetBits}(\mathbf{x} \oplus \mathbf{y})\]\[ score = {1 \over 1 + d } \]
+ +余弦相似度返回一个介于 -1 和 1 之间的数值,而由于 OpenSearch 的相关性评分(Relevance Score)不能低于 0,k-NN 插件会加上 1 来得到最终评分。 diff --git a/i18n/zh/search-plugins/knn/nested-search-knn.md b/i18n/zh/search-plugins/knn/nested-search-knn.md new file mode 100644 index 00000000..ecb31134 --- /dev/null +++ b/i18n/zh/search-plugins/knn/nested-search-knn.md @@ -0,0 +1,334 @@ +--- +title: 使用嵌套字段的 k-NN 搜索 +--- + +# 使用嵌套字段的 k-NN 搜索 + +在 k 最近邻(k-NN)索引中使用[嵌套字段](/field-types/supported-field-types/nested),可以在单个文档中存储多个向量(Vector)。例如,如果文档由多个组成部分构成,你可以为每个组成部分生成一个向量值,并将每个向量存储在嵌套字段中。 + +k-NN 文档搜索在字段级别进行。对于包含嵌套字段的文档,OpenSearch 只检查与查询向量最近的那个向量,以决定是否将该文档纳入结果。例如,假设一个索引包含文档 `A` 和 `B`。文档 `A` 由向量 `A1` 和 `A2` 表示,文档 `B` 由向量 `B1` 表示。此外,对于查询 Q,相似度顺序为 `A1`、`A2`、`B1`。如果使用查询 Q 并将 k 值设为 2 进行搜索,搜索将同时返回文档 `A` 和 `B`,而不是只返回文档 `A`。 + +请注意,在近似搜索的情况下,结果是近似值,而不是精确匹配。 + +Lucene 和 Faiss 引擎的 HNSW 算法支持使用嵌套字段的 k-NN 搜索。 + +## 索引和搜索嵌套字段 + +要对嵌套字段使用 k-NN 搜索,必须将 `index.knn` 设置为 `true` 来创建 k-NN 索引。将字段的 `type` 设置为 `nested` 即可创建嵌套字段,并在嵌套字段中指定一个或多个 `knn_vector` 数据类型(data type)的字段。在本例中,`knn_vector` 字段 `my_vector` 嵌套在 `nested_field` 字段中: + +```json +PUT my-knn-index-1 +{ + "settings": { + "index": { + "knn": true + } + }, + "mappings": { + "properties": { + "nested_field": { + "type": "nested", + "properties": { + "my_vector": { + "type": "knn_vector", + "dimension": 3, + "method": { + "name": "hnsw", + "space_type": "l2", + "engine": "lucene", + "parameters": { + "ef_construction": 100, + "m": 16 + } + } + } + } + } + } + } +} +``` + +创建索引后,向其中添加一些数据: + +```json +PUT _bulk?refresh=true +{ "index": { "_index": "my-knn-index-1", "_id": "1" } } +{"nested_field":[{"my_vector":[1,1,1]},{"my_vector":[2,2,2]},{"my_vector":[3,3,3]}]} +{ "index": { "_index": "my-knn-index-1", "_id": "2" } } +{"nested_field":[{"my_vector":[10,10,10]},{"my_vector":[20,20,20]},{"my_vector":[30,30,30]}]} +``` + +然后使用 `knn` 查询类型对数据运行 k-NN 搜索: + +```json +GET my-knn-index-1/_search +{ + "query": { + "nested": { + "path": "nested_field", + "query": { + "knn": { + "nested_field.my_vector": { + "vector": [1,1,1], + "k": 2 + } + } + } + } + } +} +``` + +尽管与查询向量最近的三个向量都在文档 1 中,但由于 k 设置为 2,查询会同时返回文档 1 和 2: + +```json +{ + "took": 23, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "my-knn-index-1", + "_id": "1", + "_score": 1, + "_source": { + "nested_field": [ + { + "my_vector": [ + 1, + 1, + 1 + ] + }, + { + "my_vector": [ + 2, + 2, + 2 + ] + }, + { + "my_vector": [ + 3, + 3, + 3 + ] + } + ] + } + }, + { + "_index": "my-knn-index-1", + "_id": "2", + "_score": 0.0040983604, + "_source": { + "nested_field": [ + { + "my_vector": [ + 10, + 10, + 10 + ] + }, + { + "my_vector": [ + 20, + 20, + 20 + ] + }, + { + "my_vector": [ + 30, + 30, + 30 + ] + } + ] + } + } + ] + } +} +``` + +## 对嵌套字段进行带过滤的 k-NN 搜索 + +你可以对使用嵌套字段的 k-NN 搜索应用过滤器。过滤器既可以应用于顶层字段,也可以应用于嵌套字段内部的字段。 + +以下示例对顶层字段应用过滤器。 + +首先,创建一个包含嵌套字段的 k-NN 索引: + +```json +PUT my-knn-index-1 +{ + "settings": { + "index": { + "knn": true + } + }, + "mappings": { + "properties": { + "nested_field": { + "type": "nested", + "properties": { + "my_vector": { + "type": "knn_vector", + "dimension": 3, + "method": { + "name": "hnsw", + "space_type": "l2", + "engine": "lucene", + "parameters": { + "ef_construction": 100, + "m": 16 + } + } + } + } + } + } + } +} +``` + +创建索引后,向其中添加一些数据: + +```json +PUT _bulk?refresh=true +{ "index": { "_index": "my-knn-index-1", "_id": "1" } } +{"parking": false, "nested_field":[{"my_vector":[1,1,1]},{"my_vector":[2,2,2]},{"my_vector":[3,3,3]}]} +{ "index": { "_index": "my-knn-index-1", "_id": "2" } } +{"parking": true, "nested_field":[{"my_vector":[10,10,10]},{"my_vector":[20,20,20]},{"my_vector":[30,30,30]}]} +{ "index": { "_index": "my-knn-index-1", "_id": "3" } } +{"parking": true, "nested_field":[{"my_vector":[100,100,100]},{"my_vector":[200,200,200]},{"my_vector":[300,300,300]}]} +``` + +然后使用带过滤器的 `knn` 查询类型对数据运行 k-NN 搜索。以下查询返回 `parking` 字段设置为 `true` 的文档: + +```json +GET my-knn-index-1/_search +{ + "query": { + "nested": { + "path": "nested_field", + "query": { + "knn": { + "nested_field.my_vector": { + "vector": [ + 1, + 1, + 1 + ], + "k": 3, + "filter": { + "term": { + "parking": true + } + } + } + } + } + } + } +} +``` + +尽管与查询向量最近的三个向量都在文档 1 中,但由于文档 1 被过滤掉了,查询返回的是文档 2 和 3: + +```json +{ + "took": 10, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.0040983604, + "hits": [ + { + "_index": "my-knn-index-1", + "_id": "2", + "_score": 0.0040983604, + "_source": { + "parking": true, + "nested_field": [ + { + "my_vector": [ + 10, + 10, + 10 + ] + }, + { + "my_vector": [ + 20, + 20, + 20 + ] + }, + { + "my_vector": [ + 30, + 30, + 30 + ] + } + ] + } + }, + { + "_index": "my-knn-index-1", + "_id": "3", + "_score": 3.400898E-5, + "_source": { + "parking": true, + "nested_field": [ + { + "my_vector": [ + 100, + 100, + 100 + ] + }, + { + "my_vector": [ + 200, + 200, + 200 + ] + }, + { + "my_vector": [ + 300, + 300, + 300 + ] + } + ] + } + } + ] + } +} +``` diff --git a/i18n/zh/search-plugins/knn/painless-functions.md b/i18n/zh/search-plugins/knn/painless-functions.md new file mode 100644 index 00000000..cf88b04f --- /dev/null +++ b/i18n/zh/search-plugins/knn/painless-functions.md @@ -0,0 +1,63 @@ +--- +title: k-NN Painless 扩展 +--- + +# k-NN Painless 脚本扩展 + +借助 k-NN 插件的 Painless 脚本扩展,你可以在 Painless 脚本中直接使用 k-NN 距离函数,对 `knn_vector` 字段执行操作。Painless 针对每个上下文都有严格的允许使用的函数和类列表,以确保脚本的安全性。k-NN 插件为 [k-NN 评分脚本](/search-plugins/knn/knn-score-script)中使用的部分距离函数添加了 Painless 脚本扩展,因此你可以使用它们来自定义 k-NN 工作负载。 + +## k-NN Painless 脚本函数入门 {#get-started-with-k-nns-painless-scripting-functions} + +要使用 k-NN 的 Painless 脚本函数,首先按照 [k-NN 评分脚本](/search-plugins/knn/knn-score-script#getting-started-with-the-score-script-for-vectors)中的方法创建一个包含 `knn_vector` 字段的索引。创建索引并摄取一些数据后,就可以使用 Painless 扩展了: + +```json +GET my-knn-index-2/_search +{ + "size": 2, + "query": { + "script_score": { + "query": { + "bool": { + "filter": { + "term": { + "color": "BLUE" + } + } + } + }, + "script": { + "source": "1.0 + cosineSimilarity(params.query_value, doc[params.field])", + "params": { + "field": "my_vector", + "query_value": [9.9, 9.9] + } + } + } + } +} +``` + +`field` 必须映射到一个 `knn_vector` 字段,`query_value` 必须是一个与 `field` 维度相同的浮点数组。 + +## 函数类型 +下表介绍了 k-NN 插件提供的可用 Painless 函数: + +函数名称 | 函数签名 | 描述 +:--- | :--- +l2Squared | `float l2Squared (float[] queryVector, doc['vector field'])` | 此函数计算给定查询向量与文档向量之间 L2 距离(欧氏距离)的平方。距离越短,文档的相关性越高,因此本示例对 l2Squared 函数的返回值取倒数。如果文档向量与查询向量相同,结果为 0,因此本示例还会给距离加 1,以避免除以零的错误。 +l1Norm | `float l1Norm (float[] queryVector, doc['vector field'])` | 此函数计算给定查询向量与文档向量之间 L2 距离(欧氏距离)的平方。距离越短,文档的相关性越高,因此本示例对 l2Squared 函数的返回值取倒数。如果文档向量与查询向量相同,结果为 0,因此本示例还会给距离加 1,以避免除以零的错误。 +cosineSimilarity | `float cosineSimilarity (float[] queryVector, doc['vector field'])` | 余弦相似度是查询向量与文档向量在都归一化为长度 1 之后的内积。如果查询向量的模在整个查询过程中不变,你可以传入查询向量的模来提高性能,而不必针对每个过滤后的文档每次都计算一遍:
`float cosineSimilarity (float[] queryVector, doc['vector field'], float normQueryVector)`
一般来说,余弦相似度的取值范围是 [-1, 1]。但在信息检索中,由于 tf-idf 统计量不可能为负,两个文档的余弦相似度范围是 0 到 1。因此,k-NN 插件会加上 1.0,以确保始终得到正的余弦相似度评分。 + +## 约束 + +1. 如果文档的 `knn_vector` 字段与查询的维度不同,函数会抛出 `IllegalArgumentException`。 + +2. 如果向量字段没有值,函数会抛出 IllegalStateException。 + + 你可以先检查文档的该字段是否有值,以避免这种情况: + + ``` + "source": "doc[params.field].size() == 0 ? 0 : 1 / (1 + l2Squared(params.query_value, doc[params.field]))", + ``` + + 由于评分只能为正数,此脚本会将有向量字段的文档排在没有向量字段的文档之前。 diff --git a/i18n/zh/search-plugins/knn/performance-tuning.md b/i18n/zh/search-plugins/knn/performance-tuning.md new file mode 100644 index 00000000..8008a582 --- /dev/null +++ b/i18n/zh/search-plugins/knn/performance-tuning.md @@ -0,0 +1,98 @@ +--- +title: 性能调优 +--- + +# 性能调优 + +本主题提供性能调优建议,用于提高近似 k-NN(approximate k-NN,ANN)的索引和搜索性能。从整体上看,k-NN 按以下原则工作: +* 本地库索引按每个 knn_vector 字段 /(Lucene)段对创建。 +* 查询在分片内按顺序在各个段上执行(与其他任何 OpenSearch 查询相同)。 +* 段中的每个本地库索引返回 <=k 个邻居。 +* 协调节点从每个分片返回的邻居中选取最终 size 数量的邻居。 + +本主题还提供了将近似 k-NN 与使用评分脚本的精确 k-NN 进行比较的建议。 + +## 索引性能调优 + +采取以下步骤来提高索引性能,尤其是在你计划一次性索引大量向量时: + +* **禁用刷新间隔** + + 禁用刷新间隔(默认值 = 1 秒),或为刷新间隔设置较长的时长,以避免创建多个小段: + + ```json + PUT //_settings + { + "index" : { + "refresh_interval" : "-1" + } + } + ``` + **注意**:索引完成后,务必重新启用 `refresh_interval`。 + +* **禁用副本(不使用 OpenSearch 副本分片)** + + 将副本数设置为 `0`,以避免在主分片和副本分片中重复构建本地库索引。索引完成后再启用副本时,序列化的本地库索引会被直接复制。如果没有副本,丢失节点可能会导致数据丢失,因此数据必须在其他地方另有存储,以便在出现问题时可以重试这次初始加载。 + +* **增加索引线程数** + + 如果你选择的硬件有多个核心,可以在本地库索引构建中使用多个线程,从而加快索引过程。使用 [knn.algo_param.index_thread_qty](/search-plugins/knn/settings#cluster-settings) 设置确定要分配的线程数。 + + 请密切关注 CPU 使用率并选择合适的线程数。由于本地库索引构建的开销很大,使用多个线程可能会带来额外的 CPU 负载。 + +## 搜索性能调优 + +采取以下步骤来提高搜索性能: + +* **减少段数量** + + 为了提高搜索性能,必须控制段的数量。Lucene 的 IndexSearcher 会搜索分片中的所有段,以找出 'size' 个最佳结果。 + + 理想情况下,每个分片只有一个段,在搜索延迟方面可以提供最佳性能。你可以将索引配置为包含多个分片,以避免出现超大分片并获得更高的并行度。 + + 你可以通过选择更长的刷新间隔来控制段的数量,或者在索引期间通过禁用刷新间隔,让 OpenSearch 放慢段的创建。 + +* **预热索引** + + 本地库索引在索引期间构建,但会在首次搜索时加载到内存中。在 Lucene 中,每个段按顺序进行搜索(因此对于 k-NN,每个段最多返回查询点的 k 个最近邻),然后在分片级别,从各段返回的所有结果中按评分返回前 'size' 个结果(评分越高 = 结果越好)。 + + 本地库索引加载后(本地库索引加载在 OpenSearch JVM 之外),OpenSearch 会将其缓存在内存中。最初的查询开销较大,需要几秒钟,而后续查询更快,只需几毫秒(假设未触发 k-NN 熔断器)。 + + 为了避免首次查询时的延迟损失,你可以对要搜索的索引使用预热(warmup)API 操作: + + ```json + GET /_plugins/_knn/warmup/index1,index2,index3?pretty + { + "_shards" : { + "total" : 6, + "successful" : 6, + "failed" : 0 + } + } + ``` + + 预热 API 操作会将指定索引所有分片(主分片和副本分片)的所有本地库索引加载到缓存中,因此在初始搜索时不会因加载本地库索引而产生损失。 + + **注意**:此 API 操作只会将它***看到的***索引段加载到缓存中。如果在 API 运行之后有合并或刷新操作完成,或者你添加了新文档,则需要重新运行该 API,将这些本地库索引加载到内存中。 + +* **避免读取存储字段** + + 如果你的用例只是读取最近邻的 ID 和评分,可以禁用读取存储字段,从而节省从存储字段中检索向量的时间。 + +* **使用 `mmap` 文件 I/O** + + 对于基于 Lucene 的近似 k-NN 搜索,没有专门用于加速读写操作的缓存层。相反,该插件依赖 OpenSearch 核心中现有的缓存机制。在 2.4 及更早版本的基于 Lucene 的近似 k-NN 搜索中,读写操作默认基于 Java NIO,速度可能较慢,具体取决于 Lucene 版本和每个分片的段数。从 2.5 版本开始,当存储类型为 `hybridfs`(OpenSearch 中的默认存储类型)时,k-NN 默认启用 [`mmap`](https://en.wikipedia.org/wiki/Mmap) 文件 I/O。这样可以实现快速的文件 I/O 操作,并提高数据摄取和搜索的整体性能。使用 `mmap` 的两个向量值专用文件扩展名是 `.vec` 和 `.vem`。有关这些文件扩展名的更多信息,请参阅 [Lucene 文档](https://lucene.apache.org/core/9_0_0/core/org/apache/lucene/codecs/lucene90/Lucene90HnswVectorsFormat.html)。 + + `mmap` 文件 I/O 使用系统文件缓存,而不是为 Java 堆分配的内存,因此不需要额外分配内存。要更改插件设置的默认扩展名列表,请使用[集群设置 API](/api-reference/cluster-api/cluster-settings) 在集群级别更新 `index.store.hybrid.mmap.extensions` 设置。**注意**:这是一项专家级设置,更新前需要关闭索引,更新后再重新打开。 + +## 提高召回率 + +召回率取决于多种因素,例如向量数量、维度数、段等。在大量小段上搜索并聚合结果,比在少量大段上搜索并聚合结果能获得更好的召回率。本地库索引越大,如果使用较小的算法参数,召回率下降的可能性就越大。为算法参数选择较大的值应该有助于解决这个问题,但会牺牲搜索延迟和索引时间。因此,重要的是了解系统对延迟和精度的要求,然后基于实验来选择索引应包含的段数。 + +默认参数适用于较广泛的用例,但请务必在自己的数据集上进行实验并选择合适的值。有关索引级设置,请参阅[索引设置](/search-plugins/knn/knn-index#index-settings)。 + +## 近似最近邻与评分脚本的对比 + +标准 k-NN 查询和自定义评分选项的性能表现不同。请使用一组有代表性的文档进行测试,看看搜索结果和延迟是否符合你的预期。 + +如果初始过滤器能将文档数量减少到不超过 20,000 个,则自定义评分的效果最好。增加分片数可以改善延迟,但请确保分片大小保持在[推荐的指导范围](/intro#primary-and-replica-shards)内。 diff --git a/i18n/zh/search-plugins/knn/settings.md b/i18n/zh/search-plugins/knn/settings.md new file mode 100644 index 00000000..8c7048e8 --- /dev/null +++ b/i18n/zh/search-plugins/knn/settings.md @@ -0,0 +1,23 @@ +--- +title: 设置 +--- + +# k-NN 设置 + +k-NN 插件新增了若干集群设置。要详细了解静态设置和动态设置,请参阅[配置 OpenSearch](/install-and-configure/configuring-opensearch/)。 + +## 集群设置 + +设置 | 默认值 | 描述 +:--- | :--- | :--- +`knn.algo_param.index_thread_qty` | 1 | 用于创建本地库索引的线程数。将此值设置得较低可以降低 k-NN 插件对 CPU 的影响,但也会降低索引性能。 +`knn.cache.item.expiry.enabled` | false | 是否将一段时间内未被访问的本地库索引从内存中移除。 +`knn.cache.item.expiry.minutes` | 3h | 启用后,本地库索引在被从内存中移除之前的空闲时间。 +`knn.circuit_breaker.unset.percentage` | 75% | 熔断器(circuit breaker)的本地内存使用阈值。内存使用量必须低于 `knn.memory.circuit_breaker.limit` 的这一百分比,`knn.circuit_breaker.triggered` 才会保持为 false。 +`knn.circuit_breaker.triggered` | false | 当内存使用量超过 `knn.circuit_breaker.unset.percentage` 的值时为 True。 +`knn.memory.circuit_breaker.limit` | 50% | 本地库索引的本地内存上限。在默认值下,如果一台机器有 100 GB 内存且 JVM 使用了 32 GB,则 k-NN 插件会使用剩余 68 GB 的 50%(34 GB)。如果内存使用量超过此值,k-NN 会移除最近最少使用的本地库索引。 +`knn.memory.circuit_breaker.enabled` | true | 是否启用 k-NN 内存熔断器。 +`knn.plugin.enabled`| true | 启用或禁用 k-NN 插件。 +`knn.model.index.number_of_shards`| 1 | 模型系统索引所使用的分片数。模型系统索引是用于存储近似最近邻(Approximate Nearest Neighbor,ANN)搜索所用模型的 OpenSearch 索引。 +`knn.model.index.number_of_replicas`| 1 | 模型系统索引所使用的副本分片数。通常,在多节点集群中,此值应至少为 1,以提高稳定性。 +`knn.advanced.filtered_exact_search_threshold`| null | 在带过滤的 ANN 搜索中,用于切换到精确搜索的已过滤 ID 数量阈值。如果某个段中已过滤的 ID 数量小于此设置的值,则会对这些已过滤的 ID 执行精确搜索。 diff --git a/i18n/zh/search-plugins/multimodal-search.md b/i18n/zh/search-plugins/multimodal-search.md new file mode 100644 index 00000000..8b815a19 --- /dev/null +++ b/i18n/zh/search-plugins/multimodal-search.md @@ -0,0 +1,124 @@ +--- +title: 多模态搜索 +--- + +# 多模态搜索 + + +使用多模态搜索(multimodal search)可以搜索文本和图像数据。在神经搜索(Neural Search)中,文本搜索借助多模态嵌入模型来实现。 + +::: info 注意 +**前提条件**
+在使用文本搜索之前,必须先设置一个多模态嵌入模型。有关更多信息,请参阅[选择模型](/ml-commons-plugin/integrating-ml-models#choosing-a-model)。 +::: + +## 使用多模态搜索 + +要使用基于文本和图像嵌入的神经搜索,请按照以下步骤操作: + +1. [创建摄取管道](#step-1-create-an-ingest-pipeline)。 +1. [创建用于摄取的索引](#step-2-create-an-index-for-ingestion)。 +1. [将文档摄取到索引中](#step-3-ingest-documents-into-the-index)。 +1. [使用神经搜索来搜索索引](#step-4-search-the-index-using-neural-search)。 + +## 第 1 步:创建摄取管道 + +要生成向量嵌入(embedding),你需要创建一个[摄取管道](/api-reference/ingest-apis/)(Ingest Pipeline),其中包含一个 [`text_image_embedding` 处理器](/ingest-pipelines/processors/text-image-embedding),它会将文档字段中的文本或图像转换为向量嵌入。处理器的 `field_map` 决定了从哪些文本和图像字段生成向量嵌入,以及将嵌入存储到哪个输出向量字段中。 + +以下示例请求创建了一个摄取管道,其中来自 `image_description` 的文本和来自 `image_binary` 的图像将被转换为文本嵌入,嵌入将存储在 `vector_embedding` 中: + +```json +PUT /_ingest/pipeline/nlp-ingest-pipeline +{ + "description": "A text/image embedding pipeline", + "processors": [ + { + "text_image_embedding": { + "model_id": "-fYQAosBQkdnhhBsK593", + "embedding": "vector_embedding", + "field_map": { + "text": "image_description", + "image": "image_binary" + } + } + } + ] +} +``` + +## 第 2 步:创建用于摄取的索引 + +为了使用管道中定义的文本嵌入处理器,请创建一个 k-NN 索引,并将上一步创建的管道添加为默认管道。确保 `field_map` 中定义的字段被映射为正确的类型。继续这个示例,`vector_embedding` 字段必须映射为 k-NN 向量,且其维度与模型维度一致。同样,`image_description` 字段应映射为 `text`,`image_binary` 应映射为 `binary`。 + +以下示例请求创建一个设置了默认摄取管道的 k-NN 索引: + +```json +PUT /my-nlp-index +{ + "settings": { + "index.knn": true, + "default_pipeline": "nlp-ingest-pipeline", + "number_of_shards": 2 + }, + "mappings": { + "properties": { + "vector_embedding": { + "type": "knn_vector", + "dimension": 1024, + "method": { + "name": "hnsw", + "engine": "lucene", + "parameters": {} + } + }, + "image_description": { + "type": "text" + }, + "image_binary": { + "type": "binary" + } + } + } +} +``` + +有关创建 k-NN 索引及其支持的方法的更多信息,请参阅 [k-NN 索引](/search-plugins/knn/knn-index)。 + +## 第 3 步:将文档摄取到索引中 + +要将文档摄取到上一步创建的索引中,请发送以下请求: + +```json +PUT /nlp-index/_doc/1 +{ + "image_description": "Orange table", + "image_binary": "iVBORw0KGgoAAAANSUI..." +} +``` + +在文档被摄取到索引之前,摄取管道会对文档运行 `text_image_embedding` 处理器,为 `image_description` 和 `image_binary` 字段生成向量嵌入。除了原有的 `image_description` 和 `image_binary` 字段外,索引后的文档还包含 `vector_embedding` 字段,其中存储了组合后的向量嵌入。 + +## 第 4 步:使用神经搜索来搜索索引 + +要对索引执行向量搜索,请在 [k-NN 插件 API](/search-plugins/knn/api#search-model) 或 [Query DSL](/query-dsl/) 查询中使用 `neural` 查询子句。你可以使用 [k-NN 搜索过滤器](/search-plugins/knn/filter-search-knn)来细化结果。你可以按文本、图像或同时按文本和图像进行搜索。 + +以下示例请求使用 neural 查询来搜索文本和图像: + +```json +GET /my-nlp-index/_search +{ + "size": 10, + "query": { + "neural": { + "vector_embedding": { + "query_text": "Orange table", + "query_image": "iVBORw0KGgoAAAANSUI...", + "model_id": "-fYQAosBQkdnhhBsK593", + "k": 5 + } + } + } +} +``` + +为了避免在每个 neural 查询请求中都传递模型 ID,你可以在 k-NN 索引或字段上设置默认模型。要了解更多信息,请参阅[在索引或字段上设置默认模型](/search-plugins/semantic-search##setting-a-default-model-on-an-index-or-field)。 diff --git a/i18n/zh/search-plugins/neural-search-tutorial.md b/i18n/zh/search-plugins/neural-search-tutorial.md new file mode 100644 index 00000000..20980b3e --- /dev/null +++ b/i18n/zh/search-plugins/neural-search-tutorial.md @@ -0,0 +1,996 @@ +--- +title: 神经搜索教程 +--- + +# 神经搜索教程 + +默认情况下,OpenSearch 使用 [Okapi BM25](https://en.wikipedia.org/wiki/Okapi_BM25) 算法计算文档评分。BM25 是一种基于关键词的算法,在包含关键词的查询上表现良好,但无法捕捉查询词的语义。与基于关键词的搜索不同,语义搜索(semantic search)会考虑查询在搜索上下文中的含义。因此,当查询需要自然语言理解时,语义搜索的表现会很好。 + +在本教程中,你将学习如何使用神经搜索(Neural Search)来: + +- 在 OpenSearch 中实现语义搜索。 +- 通过结合语义搜索和关键词搜索(keyword search)来实现混合搜索(Hybrid Search),从而提高搜索相关性(search relevance)。 + +## 术语 + +在开始本教程之前,了解以下术语会很有帮助: + +- *神经搜索*:在摄取时和搜索时支持向量搜索: + - 在摄取时,神经搜索使用语言模型从文档的文本字段生成向量嵌入(embedding)。随后,同时包含原始文本字段及该字段向量嵌入的文档会被索引到 k-NN 索引中,如下图所示。 + + ![摄取时的神经搜索示意图](/images/neural-search-ingestion.png) + - 在搜索时,当你使用 *neural 查询* 时,查询文本会经过语言模型处理,得到的向量嵌入会与文档文本的向量嵌入进行比较,以找出最相关的结果,如下图所示。 + + ![搜索时的神经搜索示意图](/images/neural-search-query.png) + +- *语义搜索*:利用神经搜索来确定用户查询在搜索上下文中的意图,从而提高搜索相关性。 + +- *混合搜索*:结合语义搜索和关键词搜索来提高搜索相关性。 + +## 用于语义搜索的 OpenSearch 组件 + +在本教程中,你将使用以下 OpenSearch 组件来实现语义搜索: + +- [模型组](/ml-commons-plugin/model-access-control#model-groups) +- [OpenSearch 提供的预训练语言模型](/ml-commons-plugin/pretrained-models) +- [摄取管道](/api-reference/ingest-apis/) +- [k-NN 向量](/field-types/supported-field-types/knn-vector) +- [神经搜索](/search-plugins/neural-search) +- [搜索管道](/search-plugins/search-pipelines/) +- [归一化处理器](/search-plugins/search-pipelines/normalization-processor) +- [Hybrid 查询](/query-dsl/compound/hybrid) + +在学习本教程的过程中,你会看到对所有这些组件的说明,所以即使对其中一些组件不熟悉也不必担心。上面列表中的每个链接都会带你前往相应组件的文档章节。 + +## 先决条件 + +在这个简单的设置中,你将使用 OpenSearch 提供的机器学习(ML)模型,以及一个没有专用 ML 节点的集群。为确保这个基本的本地设置能够正常工作,请发送以下请求来更新与 ML 相关的集群设置: + +```json +PUT _cluster/settings +{ + "persistent": { + "plugins": { + "ml_commons": { + "only_run_on_ml_node": "false", + "model_access_control_enabled": "true", + "native_memory_threshold": "99" + } + } + } +} +``` + +#### 进阶 + +对于[自定义本地模型](/ml-commons-plugin/custom-local-models)的设置,请注意以下要求: + +- 要注册自定义本地模型,需要额外指定 `"allow_registering_model_via_url": "true"` 集群设置。 +- 在生产环境中,最佳实践是通过设置专用 ML 节点来隔离工作负载。在具有专用 ML 节点的集群上,请指定 `"only_run_on_ml_node": "true"` 以提高性能。 + +有关 ML 相关集群设置的更多信息,请参阅 [ML Commons 集群设置](/ml-commons-plugin/cluster-settings)。 + +## 教程概览 + +本教程包括以下步骤: + +1. [**设置 ML 语言模型**](#step-1-set-up-an-ml-language-model)。 + 1. [选择语言模型](#step-1a-choose-a-language-model)。 + 1. [注册模型组](#step-1b-register-a-model-group)。 + 1. [将模型注册到模型组](#step-1c-register-the-model-to-the-model-group)。 + 1. [部署模型](#step-1d-deploy-the-model)。 +1. [**使用神经搜索摄取数据**](#step-2-ingest-data-with-neural-search)。 + 1. [为神经搜索创建摄取管道](#step-2a-create-an-ingest-pipeline-for-neural-search)。 + 1. [创建 k-NN 索引](#step-2b-create-a-k-nn-index)。 + 1. [将文档摄取到索引中](#step-2c-ingest-documents-into-the-index)。 +1. [**搜索数据**](#step-3-search-the-data)。 + - [使用关键词搜索进行搜索](#search-using-a-keyword-search)。 + - [使用神经搜索进行搜索](#search-using-a-neural-search)。 + - [使用混合搜索进行搜索](#search-using-a-hybrid-search)。 + +教程中的某些步骤包含可选的 `Test it`(测试一下)部分。你可以运行这些部分中的请求,来确认该步骤是否成功。 + +完成后,请按照[清理](#clean-up)部分中的步骤删除所有已创建的组件。 + +## 教程 + +你可以使用命令行或 OpenSearch Dashboards 的[开发工具控制台](/dashboards/dev-tools/run-queries)来学习本教程。 + +## 第 1 步:设置 ML 语言模型 + +无论是在摄取时还是查询时,神经搜索都需要一个语言模型来从文本字段生成向量嵌入。 + +### 第 1(a) 步:选择语言模型 {#step-1a-choose-a-language-model} + +在本教程中,你将使用 Hugging Face 的 [DistilBERT](https://huggingface.co/docs/transformers/model_doc/distilbert) 模型。它是 OpenSearch 中可用的预训练句子转换器(sentence transformer)模型之一,在基准测试中取得了名列前茅的结果(详情请参阅[这篇博客文章](https://opensearch.org/blog/semantic-science-benchmarks/))。注册该模型时需要用到它的名称、版本和维度。你可以在[预训练模型表](/ml-commons-plugin/pretrained-models#sentence-transformers)中,通过选择与该模型 TorchScript 制品对应的 `config_url` 链接找到这些信息: + +- 模型名称为 `huggingface/sentence-transformers/msmarco-distilbert-base-tas-b`。 +- 模型版本为 `1.0.1`。 +- 该模型的维度数为 `768`。 + +::: warning 重要 +请记下该模型的维度,因为在设置 k-NN 索引时会用到它。 +::: + +#### 进阶:使用其他模型 + +此外,你也可以为模型选择以下选项之一: + +- 使用 OpenSearch 提供的任何其他预训练模型。有关更多信息,请参阅 [OpenSearch 提供的预训练模型](/ml-commons-plugin/pretrained-models)。 + +- 将你自己的模型上传到 OpenSearch。有关更多信息,请参阅[自定义本地模型](/ml-commons-plugin/custom-local-models)。 + +- 连接到托管在外部平台上的基础模型。有关更多信息,请参阅[连接到远程模型](/ml-commons-plugin/remote-models/)。 + +有关如何选择模型的信息,请参阅[延伸阅读](#further-reading)。 + +### 第 1(b) 步:注册模型组 {#step-1b-register-a-model-group} + +为了进行访问控制,模型被组织到模型组(model group)中(即某个特定模型各个版本的集合)。集群中的每个模型组名称都必须全局唯一。注册模型组可以确保模型组名称的唯一性。 + +::: tip 提示 +如果你在未事先注册模型组的情况下注册某个模型的第一个版本,系统会自动创建一个新的模型组。有关更多信息,请参阅[模型访问控制](/ml-commons-plugin/model-access-control)。 +::: + +要注册一个访问模式设置为 `public` 的模型组,请发送以下请求: + +```json +POST /_plugins/_ml/model_groups/_register +{ + "name": "NLP_model_group", + "description": "A model group for NLP models", + "access_mode": "public" +} +``` + +OpenSearch 会返回模型组 ID: + +```json +{ + "model_group_id": "Z1eQf4oB5Vm0Tdw8EIP2", + "status": "CREATED" +} +``` + +你将使用此 ID 把所选模型注册到该模型组。 + +
+ + 测试一下 + + +在请求中提供模型组 ID,搜索新创建的模型组: + +```json +POST /_plugins/_ml/model_groups/_search +{ + "query": { + "match": { + "_id": "Z1eQf4oB5Vm0Tdw8EIP2" + } + } +} +``` + +响应中包含该模型组: + +```json +{ + "took": 0, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": ".plugins-ml-model-group", + "_id": "Z1eQf4oB5Vm0Tdw8EIP2", + "_version": 1, + "_seq_no": 14, + "_primary_term": 2, + "_score": 1, + "_source": { + "created_time": 1694357262582, + "access": "public", + "latest_version": 0, + "last_updated_time": 1694357262582, + "name": "NLP_model_group", + "description": "A model group for NLP models" + } + } + ] + } +} +``` +
+ +### 第 1(c) 步:将模型注册到模型组 {#step-1c-register-the-model-to-the-model-group} + +要将模型注册到模型组,请在注册请求中提供模型组 ID: + +```json +POST /_plugins/_ml/models/_register +{ + "name": "huggingface/sentence-transformers/msmarco-distilbert-base-tas-b", + "version": "1.0.1", + "model_group_id": "Z1eQf4oB5Vm0Tdw8EIP2", + "model_format": "TORCH_SCRIPT" +} +``` + +注册模型是一项异步任务。OpenSearch 会返回该任务的任务 ID: + +```json +{ + "task_id": "aFeif4oB5Vm0Tdw8yoN7", + "status": "CREATED" +} +``` + +OpenSearch 会从 URL 下载模型的配置文件和模型内容。由于该模型大于 10 MB,OpenSearch 会将其拆分为最大 10 MB 的块,并将这些块保存在模型索引中。你可以使用 Tasks API 检查任务状态: + +```json +GET /_plugins/_ml/tasks/aFeif4oB5Vm0Tdw8yoN7 +``` + +任务完成后,任务状态将变为 `COMPLETED`,Tasks API 的响应中会包含已注册模型的模型 ID: + +```json +{ + "model_id": "aVeif4oB5Vm0Tdw8zYO2", + "task_type": "REGISTER_MODEL", + "function_name": "TEXT_EMBEDDING", + "state": "COMPLETED", + "worker_node": [ + "4p6FVOmJRtu3wehDD74hzQ" + ], + "create_time": 1694358489722, + "last_update_time": 1694358499139, + "is_async": true +} +``` + +在后续的几个步骤中使用该模型时,你都需要用到这个模型 ID。 + +
+ + 测试一下 + + +在请求中提供模型 ID,搜索新创建的模型: + +```json +GET /_plugins/_ml/models/aVeif4oB5Vm0Tdw8zYO2 +``` + +响应中包含该模型: + +```json +{ + "name": "huggingface/sentence-transformers/msmarco-distilbert-base-tas-b", + "model_group_id": "Z1eQf4oB5Vm0Tdw8EIP2", + "algorithm": "TEXT_EMBEDDING", + "model_version": "1", + "model_format": "TORCH_SCRIPT", + "model_state": "REGISTERED", + "model_content_size_in_bytes": 266352827, + "model_content_hash_value": "acdc81b652b83121f914c5912ae27c0fca8fabf270e6f191ace6979a19830413", + "model_config": { + "model_type": "distilbert", + "embedding_dimension": 768, + "framework_type": "SENTENCE_TRANSFORMERS", + "all_config": """{"_name_or_path":"old_models/msmarco-distilbert-base-tas-b/0_Transformer","activation":"gelu","architectures":["DistilBertModel"],"attention_dropout":0.1,"dim":768,"dropout":0.1,"hidden_dim":3072,"initializer_range":0.02,"max_position_embeddings":512,"model_type":"distilbert","n_heads":12,"n_layers":6,"pad_token_id":0,"qa_dropout":0.1,"seq_classif_dropout":0.2,"sinusoidal_pos_embds":false,"tie_weights_":true,"transformers_version":"4.7.0","vocab_size":30522}""" + }, + "created_time": 1694482261832, + "last_updated_time": 1694482324282, + "last_registered_time": 1694482270216, + "last_deployed_time": 1694482324282, + "total_chunks": 27, + "planning_worker_node_count": 1, + "current_worker_node_count": 1, + "planning_worker_nodes": [ + "4p6FVOmJRtu3wehDD74hzQ" + ], + "deploy_to_all_nodes": true +} +``` + +响应中包含模型信息。可以看到 `model_state` 为 `REGISTERED`。此外,如 `total_chunks` 字段所示,该模型被拆分成了 27 个块。 +
+ +#### 进阶:注册自定义模型 + +要注册自定义模型,必须在注册请求中提供模型配置。例如,以下注册请求包含本教程所用模型的完整格式: + +```json +POST /_plugins/_ml/models/_register +{ + "name": "sentence-transformers/msmarco-distilbert-base-tas-b", + "version": "1.0.1", + "description": "This is a port of the DistilBert TAS-B Model to sentence-transformers model: It maps sentences & paragraphs to a 768 dimensional dense vector space and is optimized for the task of semantic search.", + "model_task_type": "TEXT_EMBEDDING", + "model_format": "ONNX", + "model_content_size_in_bytes": 266291330, + "model_content_hash_value": "a3c916f24239fbe32c43be6b24043123d49cd2c41b312fc2b29f2fc65e3c424c", + "model_config": { + "model_type": "distilbert", + "embedding_dimension": 768, + "framework_type": "huggingface_transformers", + "pooling_mode": "CLS", + "normalize_result": false, + "all_config": "{\"_name_or_path\":\"old_models/msmarco-distilbert-base-tas-b/0_Transformer\",\"activation\":\"gelu\",\"architectures\":[\"DistilBertModel\"],\"attention_dropout\":0.1,\"dim\":768,\"dropout\":0.1,\"hidden_dim\":3072,\"initializer_range\":0.02,\"max_position_embeddings\":512,\"model_type\":\"distilbert\",\"n_heads\":12,\"n_layers\":6,\"pad_token_id\":0,\"qa_dropout\":0.1,\"seq_classif_dropout\":0.2,\"sinusoidal_pos_embds\":false,\"tie_weights_\":true,\"transformers_version\":\"4.7.0\",\"vocab_size\":30522}" + }, + "created_time": 1676074079195, + "model_group_id": "Z1eQf4oB5Vm0Tdw8EIP2", + "url": "https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/msmarco-distilbert-base-tas-b/1.0.1/onnx/sentence-transformers_msmarco-distilbert-base-tas-b-1.0.1-onnx.zip" +} +``` + +有关更多信息,请参阅[在 OpenSearch 中使用 ML 模型](/ml-commons-plugin/using-ml-models)。 + +### 第 1(d) 步:部署模型 {#step-1d-deploy-the-model} + +模型注册后会保存在模型索引中。接下来,你需要部署该模型。部署模型会创建一个模型实例,并将模型缓存在内存中。要部署模型,请将其模型 ID 提供给 `_deploy` 端点: + +```json +POST /_plugins/_ml/models/aVeif4oB5Vm0Tdw8zYO2/_deploy +``` + +与注册操作一样,部署操作也是异步的,因此你会在响应中得到一个任务 ID: + +```json +{ + "task_id": "ale6f4oB5Vm0Tdw8NINO", + "status": "CREATED" +} +``` + +你可以使用 Tasks API 检查任务状态: + +```json +GET /_plugins/_ml/tasks/ale6f4oB5Vm0Tdw8NINO +``` + +任务完成后,任务状态将变为 `COMPLETED`: + +```json +{ + "model_id": "aVeif4oB5Vm0Tdw8zYO2", + "task_type": "DEPLOY_MODEL", + "function_name": "TEXT_EMBEDDING", + "state": "COMPLETED", + "worker_node": [ + "4p6FVOmJRtu3wehDD74hzQ" + ], + "create_time": 1694360024141, + "last_update_time": 1694360027940, + "is_async": true +} +``` + +
+ + 测试一下 + + +在请求中提供模型 ID,搜索已部署的模型: + +```json +GET /_plugins/_ml/models/aVeif4oB5Vm0Tdw8zYO2 +``` + +响应显示模型状态为 `DEPLOYED`: + +```json +{ + "name": "huggingface/sentence-transformers/msmarco-distilbert-base-tas-b", + "model_group_id": "Z1eQf4oB5Vm0Tdw8EIP2", + "algorithm": "TEXT_EMBEDDING", + "model_version": "1", + "model_format": "TORCH_SCRIPT", + "model_state": "DEPLOYED", + "model_content_size_in_bytes": 266352827, + "model_content_hash_value": "acdc81b652b83121f914c5912ae27c0fca8fabf270e6f191ace6979a19830413", + "model_config": { + "model_type": "distilbert", + "embedding_dimension": 768, + "framework_type": "SENTENCE_TRANSFORMERS", + "all_config": """{"_name_or_path":"old_models/msmarco-distilbert-base-tas-b/0_Transformer","activation":"gelu","architectures":["DistilBertModel"],"attention_dropout":0.1,"dim":768,"dropout":0.1,"hidden_dim":3072,"initializer_range":0.02,"max_position_embeddings":512,"model_type":"distilbert","n_heads":12,"n_layers":6,"pad_token_id":0,"qa_dropout":0.1,"seq_classif_dropout":0.2,"sinusoidal_pos_embds":false,"tie_weights_":true,"transformers_version":"4.7.0","vocab_size":30522}""" + }, + "created_time": 1694482261832, + "last_updated_time": 1694482324282, + "last_registered_time": 1694482270216, + "last_deployed_time": 1694482324282, + "total_chunks": 27, + "planning_worker_node_count": 1, + "current_worker_node_count": 1, + "planning_worker_nodes": [ + "4p6FVOmJRtu3wehDD74hzQ" + ], + "deploy_to_all_nodes": true +} +``` + +你还可以发送 [Models Profile API](/ml-commons-plugin/api/profile) 请求,获取集群中所有已部署模型的统计信息: + +```json +GET /_plugins/_ml/profile/models +``` +
+ +## 第 2 步:使用神经搜索摄取数据 + +神经搜索使用语言模型将文本转换为向量嵌入。在摄取期间,神经搜索会为请求中的文本字段创建向量嵌入。在搜索期间,你可以使用同一个模型为查询文本生成向量嵌入,从而对文档执行向量相似度搜索。 + +### 第 2(a) 步:为神经搜索创建摄取管道 {#step-2a-create-an-ingest-pipeline-for-neural-search} + +模型部署完成后,就可以使用该模型来配置[神经搜索](/search-plugins/neural-search)了。首先,你需要创建一个[摄取管道](/api-reference/ingest-apis/)(Ingest Pipeline),其中包含一个处理器(Processor):处理器是在文档被摄取到索引之前对文档字段进行转换的任务。对于神经搜索,你将设置一个 `text_embedding` 处理器,用于从文本创建向量嵌入。你需要上一节中设置的模型的 `model_id`,以及一个 `field_map`,它指定从哪个字段获取文本(`text`),以及将嵌入记录到哪个字段(`passage_embedding`): + +```json +PUT /_ingest/pipeline/nlp-ingest-pipeline +{ + "description": "An NLP ingest pipeline", + "processors": [ + { + "text_embedding": { + "model_id": "aVeif4oB5Vm0Tdw8zYO2", + "field_map": { + "text": "passage_embedding" + } + } + } + ] +} +``` + +
+ + 测试一下 + + +使用 Ingest API 搜索已创建的摄取管道: + +```json +GET /_ingest/pipeline +``` + +响应中包含该摄取管道: + +```json +{ + "nlp-ingest-pipeline": { + "description": "An NLP ingest pipeline", + "processors": [ + { + "text_embedding": { + "model_id": "aVeif4oB5Vm0Tdw8zYO2", + "field_map": { + "text": "passage_embedding" + } + } + } + ] + } +} +``` +
+ +### 第 2(b) 步:创建 k-NN 索引 {#step-2b-create-a-k-nn-index} + +现在,你将创建一个 k-NN 索引,其中包含一个名为 `text` 的字段(存放图像描述),以及一个名为 `passage_embedding` 的 [`knn_vector`](/field-types/supported-field-types/knn-vector) 字段(存放文本的向量嵌入)。此外,将默认摄取管道设置为上一步创建的 `nlp-ingest-pipeline`: + +```json +PUT /my-nlp-index +{ + "settings": { + "index.knn": true, + "default_pipeline": "nlp-ingest-pipeline" + }, + "mappings": { + "properties": { + "id": { + "type": "text" + }, + "passage_embedding": { + "type": "knn_vector", + "dimension": 768, + "method": { + "engine": "lucene", + "space_type": "l2", + "name": "hnsw", + "parameters": {} + } + }, + "text": { + "type": "text" + } + } + } +} +``` + +设置好 k-NN 索引后,你就可以在之后对 `passage_embedding` 字段执行向量搜索。 + +
+ + 测试一下 + + +使用以下请求获取已创建索引的设置和映射: + +```json +GET /my-nlp-index/_settings +``` + +```json +GET /my-nlp-index/_mappings +``` + +
+ +### 第 2(c) 步:将文档摄取到索引中 {#step-2c-ingest-documents-into-the-index} + +在这一步中,你将把几个示例文档摄取到索引中。示例数据取自 [Flickr 图像数据集](https://www.kaggle.com/datasets/hsankesara/flickr-image-dataset)。每个文档都包含一个对应图像描述的 `text` 字段,以及一个对应图像 ID 的 `id` 字段: + +```json +PUT /my-nlp-index/_doc/1 +{ + "text": "A West Virginia university women 's basketball team , officials , and a small gathering of fans are in a West Virginia arena .", + "id": "4319130149.jpg" +} +``` + +```json +PUT /my-nlp-index/_doc/2 +{ + "text": "A wild animal races across an uncut field with a minimal amount of trees .", + "id": "1775029934.jpg" +} +``` + +```json +PUT /my-nlp-index/_doc/3 +{ + "text": "People line the stands which advertise Freemont 's orthopedics , a cowboy rides a light brown bucking bronco .", + "id": "2664027527.jpg" +} +``` + +```json +PUT /my-nlp-index/_doc/4 +{ + "text": "A man who is riding a wild horse in the rodeo is very near to falling off .", + "id": "4427058951.jpg" +} +``` + +```json +PUT /my-nlp-index/_doc/5 +{ + "text": "A rodeo cowboy , wearing a cowboy hat , is being thrown off of a wild white horse .", + "id": "2691147709.jpg" +} +``` + +当文档被摄取到索引中时,`text_embedding` 处理器会创建一个包含向量嵌入的附加字段,并将该字段添加到文档中。要查看已索引的示例文档,请搜索文档 1: + +```json +GET /my-nlp-index/_doc/1 +``` + +响应中包括文档的 `_source`,其中包含原始的 `text` 和 `id` 字段以及新增的 `passage_embedding` 字段: + +```json +{ + "_index": "my-nlp-index", + "_id": "1", + "_version": 1, + "_seq_no": 0, + "_primary_term": 1, + "found": true, + "_source": { + "passage_embedding": [ + 0.04491629, + -0.34105563, + 0.036822468, + -0.14139028, + ... + ], + "text": "A West Virginia university women 's basketball team , officials , and a small gathering of fans are in a West Virginia arena .", + "id": "4319130149.jpg" + } +} +``` + +## 第 3 步:搜索数据 + +现在,你将分别使用关键词搜索、神经搜索以及两者的组合来搜索索引。 + +### 使用关键词搜索进行搜索 + +要使用关键词搜索,请使用 `match` 查询。你将从结果中排除嵌入: + +```json +GET /my-nlp-index/_search +{ + "_source": { + "excludes": [ + "passage_embedding" + ] + }, + "query": { + "match": { + "text": { + "query": "wild west" + } + } + } +} +``` + +文档 3 没有被返回,因为它不包含指定的关键词。由于没有考虑语义,包含 `rodeo` 和 `cowboy` 这些词的文档评分较低: + +
+ + 结果 + + +```json +{ + "took": 647, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4, + "relation": "eq" + }, + "max_score": 1.7878418, + "hits": [ + { + "_index": "my-nlp-index", + "_id": "1", + "_score": 1.7878418, + "_source": { + "text": "A West Virginia university women 's basketball team , officials , and a small gathering of fans are in a West Virginia arena .", + "id": "4319130149.jpg" + } + }, + { + "_index": "my-nlp-index", + "_id": "2", + "_score": 0.58093566, + "_source": { + "text": "A wild animal races across an uncut field with a minimal amount of trees .", + "id": "1775029934.jpg" + } + }, + { + "_index": "my-nlp-index", + "_id": "5", + "_score": 0.55228686, + "_source": { + "text": "A rodeo cowboy , wearing a cowboy hat , is being thrown off of a wild white horse .", + "id": "2691147709.jpg" + } + }, + { + "_index": "my-nlp-index", + "_id": "4", + "_score": 0.53899646, + "_source": { + "text": "A man who is riding a wild horse in the rodeo is very near to falling off .", + "id": "4427058951.jpg" + } + } + ] + } +} +``` +
+ +### 使用神经搜索进行搜索 + +要使用神经搜索,请使用 `neural` 查询,并提供之前设置的模型的模型 ID,以便使用摄取时所用的同一模型为查询文本生成向量嵌入: + +```json +GET /my-nlp-index/_search +{ + "_source": { + "excludes": [ + "passage_embedding" + ] + }, + "query": { + "neural": { + "passage_embedding": { + "query_text": "wild west", + "model_id": "aVeif4oB5Vm0Tdw8zYO2", + "k": 5 + } + } + } +} +``` + +这一次,响应不仅包含全部五个文档,而且由于神经搜索考虑了语义,文档的排列顺序也更合理了: + +
+ + 结果 + + +```json +{ + "took": 25, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 5, + "relation": "eq" + }, + "max_score": 0.01585195, + "hits": [ + { + "_index": "my-nlp-index", + "_id": "4", + "_score": 0.01585195, + "_source": { + "text": "A man who is riding a wild horse in the rodeo is very near to falling off .", + "id": "4427058951.jpg" + } + }, + { + "_index": "my-nlp-index", + "_id": "2", + "_score": 0.015748845, + "_source": { + "text": "A wild animal races across an uncut field with a minimal amount of trees.", + "id": "1775029934.jpg" + } + }, + { + "_index": "my-nlp-index", + "_id": "5", + "_score": 0.015177963, + "_source": { + "text": "A rodeo cowboy , wearing a cowboy hat , is being thrown off of a wild white horse .", + "id": "2691147709.jpg" + } + }, + { + "_index": "my-nlp-index", + "_id": "1", + "_score": 0.013272902, + "_source": { + "text": "A West Virginia university women 's basketball team , officials , and a small gathering of fans are in a West Virginia arena .", + "id": "4319130149.jpg" + } + }, + { + "_index": "my-nlp-index", + "_id": "3", + "_score": 0.011347735, + "_source": { + "text": "People line the stands which advertise Freemont 's orthopedics , a cowboy rides a light brown bucking bronco .", + "id": "2664027527.jpg" + } + } + ] + } +} +``` +
+ +### 使用混合搜索进行搜索 + +混合搜索结合了关键词搜索和神经搜索来提高搜索相关性。要实现混合搜索,你需要设置一个在搜索时运行的[搜索管道](/search-plugins/search-pipelines/)(Search Pipeline)。你将配置的搜索管道会在中间阶段拦截搜索结果,并对其应用 [`normalization-processor`](/search-plugins/search-pipelines/normalization-processor)。`normalization-processor` 会对来自多个查询子句的文档评分进行归一化和组合,并根据所选的归一化方法(normalization technique)和组合方法(combination technique)对文档重新评分。 + +#### 第 1 步:配置搜索管道 + +要配置包含 `normalization-processor` 的搜索管道,请使用以下请求。处理器中的归一化方法设置为 `min_max`,组合方法设置为 `arithmetic_mean`。`weights` 数组以小数形式的百分比指定分配给每个查询子句的权重: + +```json +PUT /_search/pipeline/nlp-search-pipeline +{ + "description": "Post processor for hybrid search", + "phase_results_processors": [ + { + "normalization-processor": { + "normalization": { + "technique": "min_max" + }, + "combination": { + "technique": "arithmetic_mean", + "parameters": { + "weights": [ + 0.3, + 0.7 + ] + } + } + } + } + ] +} +``` + +#### 第 2 步:使用 hybrid 查询进行搜索 + +你将使用 [`hybrid` 查询](/query-dsl/compound/hybrid)来组合 `match` 和 `neural` 查询子句。请务必在查询参数中将之前创建的 `nlp-search-pipeline` 应用于该请求: + +```json +GET /my-nlp-index/_search?search_pipeline=nlp-search-pipeline +{ + "_source": { + "exclude": [ + "passage_embedding" + ] + }, + "query": { + "hybrid": { + "queries": [ + { + "match": { + "text": { + "query": "cowboy rodeo bronco" + } + } + }, + { + "neural": { + "passage_embedding": { + "query_text": "wild west", + "model_id": "aVeif4oB5Vm0Tdw8zYO2", + "k": 5 + } + } + } + ] + } + } +} +``` + +OpenSearch 不仅返回了与 `wild west` 语义相匹配的文档,而且包含与狂野西部主题相关词语的文档,其评分也比其他文档更高: + +
+ + 结果 + + +```json +{ + "took": 27, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 5, + "relation": "eq" + }, + "max_score": 0.86481035, + "hits": [ + { + "_index": "my-nlp-index", + "_id": "5", + "_score": 0.86481035, + "_source": { + "text": "A rodeo cowboy , wearing a cowboy hat , is being thrown off of a wild white horse .", + "id": "2691147709.jpg" + } + }, + { + "_index": "my-nlp-index", + "_id": "4", + "_score": 0.7003, + "_source": { + "text": "A man who is riding a wild horse in the rodeo is very near to falling off .", + "id": "4427058951.jpg" + } + }, + { + "_index": "my-nlp-index", + "_id": "2", + "_score": 0.6839765, + "_source": { + "text": "A wild animal races across an uncut field with a minimal amount of trees.", + "id": "1775029934.jpg" + } + }, + { + "_index": "my-nlp-index", + "_id": "3", + "_score": 0.3007, + "_source": { + "text": "People line the stands which advertise Freemont 's orthopedics , a cowboy rides a light brown bucking bronco .", + "id": "2664027527.jpg" + } + }, + { + "_index": "my-nlp-index", + "_id": "1", + "_score": 0.29919013, + "_source": { + "text": "A West Virginia university women 's basketball team , officials , and a small gathering of fans are in a West Virginia arena .", + "id": "4319130149.jpg" + } + } + ] + } +} +``` +
+ +你可以按如下方式将其设置为索引的默认搜索管道,而不必在每个请求中都指定搜索管道: + +```json +PUT /my-nlp-index/_settings +{ + "index.search.default_pipeline" : "nlp-search-pipeline" +} +``` + +现在你可以尝试不同的权重、归一化方法和组合方法。有关更多信息,请参阅 [`normalization-processor`](/search-plugins/search-pipelines/normalization-processor) 和 [`hybrid` 查询](/query-dsl/compound/hybrid)文档。 + +#### 进阶 {#advanced-1} + +你可以使用搜索模板对搜索进行参数化。搜索模板会隐藏实现细节,减少嵌套层级,从而降低查询的复杂度。有关更多信息,请参阅[搜索模板](/api-reference/search-template)。 + +### 清理 + +完成后,从集群中删除你在本教程中创建的组件: + +```json +DELETE /my-nlp-index +``` + +```json +DELETE /_search/pipeline/nlp-search-pipeline +``` + +```json +DELETE /_ingest/pipeline/nlp-ingest-pipeline +``` + +```json +POST /_plugins/_ml/models/aVeif4oB5Vm0Tdw8zYO2/_undeploy +``` + +```json +DELETE /_plugins/_ml/models/aVeif4oB5Vm0Tdw8zYO2 +``` + +```json +DELETE /_plugins/_ml/model_groups/Z1eQf4oB5Vm0Tdw8EIP2 +``` + +## 延伸阅读 + +- 在 [Building a semantic search engine in OpenSearch](https://opensearch.org/blog/semantic-search-solutions/) 中了解 OpenSearch 语义搜索的基础知识。 +- 在 [The ABCs of semantic search in OpenSearch: Architectures, benchmarks, and combination strategies](https://opensearch.org/blog/semantic-science-benchmarks/) 中了解结合关键词搜索与神经搜索的好处、归一化和组合方法的可选项以及基准测试。 diff --git a/i18n/zh/search-plugins/neural-search.md b/i18n/zh/search-plugins/neural-search.md new file mode 100644 index 00000000..178e05e7 --- /dev/null +++ b/i18n/zh/search-plugins/neural-search.md @@ -0,0 +1,47 @@ +--- +title: 神经搜索 +--- + +# 神经搜索 + +神经搜索(Neural Search)将文本转换为向量(vector),并在摄取和搜索时为向量搜索提供支持。在摄取期间,神经搜索将文档文本转换为向量嵌入(embedding),并在向量索引中同时为文本及其向量嵌入建立索引。在搜索时使用 neural 查询,神经搜索会将查询文本转换为向量嵌入,使用向量搜索比较查询与文档的嵌入,并返回最接近的结果。 + +在将文档摄取到索引之前,文档会先经过机器学习(ML)模型(model)处理,由模型为文档字段生成向量嵌入。发送搜索请求时,查询文本或图像同样会经过该 ML 模型,生成对应的向量嵌入。随后,神经搜索对这些嵌入执行向量搜索并返回匹配的文档。 + +## 前提条件 + +使用神经搜索之前,必须先设置 ML 模型。选择模型时有以下几种方式: + +- 使用 OpenSearch 提供的预训练模型。有关更多信息,请参阅 [OpenSearch 提供的预训练模型](/ml-commons-plugin/pretrained-models)。 + +- 将自己的模型上传到 OpenSearch。有关更多信息,请参阅[自定义本地模型](/ml-commons-plugin/custom-local-models)。 + +- 连接到托管在外部平台上的基础模型。有关更多信息,请参阅[连接远程模型](/ml-commons-plugin/remote-models/)。 + +## 教程 + +有关分步教程,请参阅[神经搜索教程](/search-plugins/neural-search-tutorial)。 + +## 使用 ML 模型进行神经搜索 + +设置好 ML 模型后,选择以下任一搜索方法,即可使用该模型进行神经搜索。 + +### 语义搜索 + +语义搜索(semantic search)使用基于文本嵌入模型的稠密检索来搜索文本数据。有关详细的设置说明,请参阅[语义搜索](/search-plugins/semantic-search)。 + +### 混合搜索 + +混合搜索(Hybrid Search)结合关键词搜索和神经搜索来提高搜索相关性。有关详细的设置说明,请参阅[混合搜索](/search-plugins/hybrid-search)。 + +### 多模态搜索 + +多模态搜索(multimodal search)将神经搜索与多模态嵌入模型结合使用,以搜索文本和图像数据。有关详细的设置说明,请参阅[多模态搜索](/search-plugins/multimodal-search)。 + +### 稀疏搜索 + +稀疏搜索(sparse search)将神经搜索与基于稀疏嵌入模型的稀疏检索结合使用,以搜索文本数据。有关详细的设置说明,请参阅[稀疏搜索](/search-plugins/neural-sparse-search)。 + +### 对话式搜索 + +借助对话式搜索(conversational search),你可以用自然语言提问、获得文本回答,并继续提出澄清性的追问。有关详细的设置说明,请参阅[对话式搜索](/search-plugins/conversational-search)。 diff --git a/i18n/zh/search-plugins/neural-sparse-search.md b/i18n/zh/search-plugins/neural-sparse-search.md new file mode 100644 index 00000000..af1f0c8f --- /dev/null +++ b/i18n/zh/search-plugins/neural-sparse-search.md @@ -0,0 +1,229 @@ +--- +title: 神经稀疏搜索 +--- + +# 神经稀疏搜索 + + +[语义搜索](/search-plugins/semantic-search)依赖基于文本嵌入(embedding)模型的稠密检索。然而,稠密方法使用 k-NN 搜索,会消耗大量内存和 CPU 资源。神经稀疏搜索(neural sparse search)是语义搜索的一种替代方案,它使用倒排索引实现,因此与 BM25 同样高效。神经稀疏搜索由稀疏嵌入模型提供支持。执行神经稀疏搜索时,它会创建一个稀疏向量(sparse vector,即由表示条目及其权重的 `token: weight` 键值对组成的列表),并将数据摄取到 rank features 索引中。 + +选择模型时,可以从以下方式中任选其一: + +- 在摄取和搜索时都使用稀疏编码模型(性能高,延迟相对较高)。 +- 在摄取时使用稀疏编码模型,在搜索时使用分词器模型(性能低,延迟相对较低)。 + +::: info 注意 +**前提条件**
+使用神经稀疏搜索之前,请确保已设置好[预训练的稀疏嵌入模型](/ml-commons-plugin/pretrained-models#sparse-encoding-models)或你自己的稀疏嵌入模型。有关更多信息,请参阅[选择模型](/ml-commons-plugin/integrating-ml-models#choosing-a-model)。 +::: + +## 使用神经稀疏搜索 + +要使用神经稀疏搜索,请按以下步骤操作: + +1. [创建摄取管道](#step-1-create-an-ingest-pipeline)。 +1. [创建用于摄取的索引](#step-2-create-an-index-for-ingestion)。 +1. [将文档摄取到索引中](#step-3-ingest-documents-into-the-index)。 +1. [使用神经搜索搜索索引](#step-4-search-the-index-using-neural-search)。 + +## 第 1 步:创建摄取管道 + +要生成向量嵌入,需要创建一个包含 [`sparse_encoding` 处理器](/ingest-pipelines/processors/sparse-encoding)的[摄取管道](/api-reference/ingest-apis/)(Ingest Pipeline),该处理器会将文档字段中的文本转换为向量嵌入。处理器的 `field_map` 决定了从哪些输入字段生成向量嵌入,以及将嵌入存储在哪些输出字段中。 + +以下示例请求创建一个摄取管道,`passage_text` 中的文本将被转换为文本嵌入,嵌入存储在 `passage_embedding` 中: + +```json +PUT /_ingest/pipeline/nlp-ingest-pipeline-sparse +{ + "description": "An sparse encoding ingest pipeline", + "processors": [ + { + "sparse_encoding": { + "model_id": "aP2Q8ooBpBj3wT4HVS8a", + "field_map": { + "passage_text": "passage_embedding" + } + } + } + ] +} +``` + +## 第 2 步:创建用于摄取的索引 + +要使用管道中定义的文本嵌入处理器,请创建一个 rank features 索引,并将上一步创建的管道设置为默认管道。确保 `field_map` 中定义的字段被映射为正确的类型。继续沿用本例,`passage_embedding` 字段必须映射为 [`rank_features`](/field-types/supported-field-types/rank#rank-features)。同样,`passage_text` 字段应映射为 `text`。 + +以下示例请求创建一个设置了默认摄取管道的 rank features 索引: + +```json +PUT /my-nlp-index +{ + "settings": { + "default_pipeline": "nlp-ingest-pipeline-sparse" + }, + "mappings": { + "properties": { + "id": { + "type": "text" + }, + "passage_embedding": { + "type": "rank_features" + }, + "passage_text": { + "type": "text" + } + } + } +} +``` + +为了节省磁盘空间,可以按如下方式将嵌入向量从 source 中排除: + +```json +PUT /my-nlp-index +{ + "settings": { + "default_pipeline": "nlp-ingest-pipeline-sparse" + }, + "mappings": { + "_source": { + "excludes": [ + "passage_embedding" + ] + }, + "properties": { + "id": { + "type": "text" + }, + "passage_embedding": { + "type": "rank_features" + }, + "passage_text": { + "type": "text" + } + } + } +} +``` + +::: warning 重要 +`` 对一旦从 source 中排除,就无法恢复。在应用此优化之前,请确保你的应用不需要这些 `` 对。 +::: + +## 第 3 步:将文档摄取到索引中 + +要将文档摄取到上一步创建的索引中,请发送以下请求: + +```json +PUT /my-nlp-index/_doc/1 +{ + "passage_text": "Hello world", + "id": "s1" +} +``` + +```json +PUT /my-nlp-index/_doc/2 +{ + "passage_text": "Hi planet", + "id": "s2" +} +``` + +在文档被摄取到索引之前,摄取管道会对文档运行 `sparse_encoding` 处理器,为 `passage_text` 字段生成向量嵌入。被索引的文档包含存放原始文本的 `passage_text` 字段,以及存放向量嵌入的 `passage_embedding` 字段。 + +## 第 4 步:使用神经搜索搜索索引 + +要对索引执行神经稀疏搜索,请在 [Query DSL](/query-dsl/) 查询中使用 `neural_sparse` 查询子句。 + +以下示例请求使用 `neural_sparse` 查询来搜索相关文档: + +```json +GET my-nlp-index/_search +{ + "query": { + "neural_sparse": { + "passage_embedding": { + "query_text": "Hi world", + "model_id": "aP2Q8ooBpBj3wT4HVS8a" + } + } + } +} +``` + +响应包含匹配的文档: + +```json +{ + "took" : 688, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 2, + "relation" : "eq" + }, + "max_score" : 30.0029, + "hits" : [ + { + "_index" : "my-nlp-index", + "_id" : "1", + "_score" : 30.0029, + "_source" : { + "passage_text" : "Hello world", + "passage_embedding" : { + "!" : 0.8708904, + "door" : 0.8587369, + "hi" : 2.3929274, + "worlds" : 2.7839446, + "yes" : 0.75845814, + "##world" : 2.5432441, + "born" : 0.2682308, + "nothing" : 0.8625516, + "goodbye" : 0.17146169, + "greeting" : 0.96817183, + "birth" : 1.2788506, + "come" : 0.1623208, + "global" : 0.4371151, + "it" : 0.42951578, + "life" : 1.5750692, + "thanks" : 0.26481047, + "world" : 4.7300377, + "tiny" : 0.5462298, + "earth" : 2.6555297, + "universe" : 2.0308156, + "worldwide" : 1.3903781, + "hello" : 6.696973, + "so" : 0.20279501, + "?" : 0.67785245 + }, + "id" : "s1" + } + }, + { + "_index" : "my-nlp-index", + "_id" : "2", + "_score" : 16.480486, + "_source" : { + "passage_text" : "Hi planet", + "passage_embedding" : { + "hi" : 4.338913, + "planets" : 2.7755864, + "planet" : 5.0969057, + "mars" : 1.7405145, + "earth" : 2.6087382, + "hello" : 3.3210192 + }, + "id" : "s2" + } + } + ] + } +} +``` diff --git a/i18n/zh/search-plugins/querqy/index.md b/i18n/zh/search-plugins/querqy/index.md new file mode 100644 index 00000000..978d7b19 --- /dev/null +++ b/i18n/zh/search-plugins/querqy/index.md @@ -0,0 +1,45 @@ +--- +title: Querqy +--- + +# Querqy + +Querqy 是一个用于查询改写的社区插件,可帮助解决相关性问题,使搜索引擎在匹配和评分方面更加精确。 + +::: danger 警告 +Querqy 目前仅支持 OpenSearch 2.3。 +::: + +## 安装 Querqy 插件 + +Querqy 插件现已支持 OpenSearch 2.3.0。运行以下命令安装 Querqy 插件。 + +````bash +./bin/opensearch-plugin install \ + "https://repo1.maven.org/maven2/org/querqy/opensearch-querqy/1.0.os2.3.0/opensearch-querqy-1.0.os2.3.0.zip" +```` + +安装过程中出现安全提示时请回答 `yes`,因为 Querqy 需要额外的权限来加载查询改写器。 + +安装 Querqy 插件后,可以在 Querqy.org 网站上找到完整的文档:[Querqy](https://docs.querqy.org/querqy/index.html) + +## 路径和 HTTP 方法 + +``` +POST /myindex/_search +``` + +## 示例查询 + +````json +{ + "query": { + "querqy": { + "matching_query": { + "query": "books" + }, + "query_fields": [ "title^3.0", "words^2.1", "shortSummary"] + } + } +} +```` diff --git a/i18n/zh/search-plugins/search-pipelines/collapse-processor.md b/i18n/zh/search-plugins/search-pipelines/collapse-processor.md new file mode 100644 index 00000000..e78216b7 --- /dev/null +++ b/i18n/zh/search-plugins/search-pipelines/collapse-processor.md @@ -0,0 +1,128 @@ +--- +title: Collapse +--- + +# Collapse 处理器 + +`collapse` 响应处理器会丢弃这样的命中(hit):其特定字段的值与结果集中前面某个文档的该字段值相同。这与在搜索请求中传递 `collapse` 参数类似,但该响应处理器是在从所有分片获取结果之后作用于响应的。`collapse` 响应处理器可以与 `rescore` 搜索请求参数配合使用,也可以在重排序响应处理器之后应用。 + +使用 `collapse` 响应处理器很可能导致返回的结果少于 `size` 个,因为命中是从一个大小已经小于或等于 `size` 的集合中丢弃的。为了提高返回 `size` 个命中的可能性,可以使用 `oversample` 请求处理器和 `truncate_hits` 响应处理器,如[此示例](/search-plugins/search-pipelines/truncate-hits-processor#oversample-collapse-and-truncate-hits)所示。 + +## 请求字段 + +下表列出了所有请求字段。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`field` | String | 从每个返回的搜索命中中读取其值的字段。对于该字段的每个值,搜索响应中只返回第一个命中。必需。 +`context_prefix` | String | 可用于从特定作用域读取 `original_size` 变量,以避免冲突。可选。 +`tag` | String | 处理器的标识符。可选。 +`description` | String | 处理器的描述。可选。 +`ignore_failure` | Boolean | 如果为 `true`,OpenSearch 会[忽略该处理器的任何失败](/search-plugins/search-pipelines/creating-search-pipeline#ignoring-processor-failures),并继续运行搜索管道中剩余的处理器。可选。默认值为 `false`。 + +## 示例 + +以下示例演示如何使用包含 `collapse` 处理器的搜索管道。 + +### 准备工作 + +创建多个文档,其中包含一个用于折叠的字段: + +```json +POST /_bulk +{ "create":{"_index":"my_index","_id":1}} +{ "title" : "document 1", "color":"blue" } +{ "create":{"_index":"my_index","_id":2}} +{ "title" : "document 2", "color":"blue" } +{ "create":{"_index":"my_index","_id":3}} +{ "title" : "document 3", "color":"red" } +{ "create":{"_index":"my_index","_id":4}} +{ "title" : "document 4", "color":"red" } +{ "create":{"_index":"my_index","_id":5}} +{ "title" : "document 5", "color":"yellow" } +{ "create":{"_index":"my_index","_id":6}} +{ "title" : "document 6", "color":"yellow" } +{ "create":{"_index":"my_index","_id":7}} +{ "title" : "document 7", "color":"orange" } +{ "create":{"_index":"my_index","_id":8}} +{ "title" : "document 8", "color":"orange" } +{ "create":{"_index":"my_index","_id":9}} +{ "title" : "document 9", "color":"green" } +{ "create":{"_index":"my_index","_id":10}} +{ "title" : "document 10", "color":"green" } +``` + +创建一个只按 `color` 字段折叠的管道: + +```json +PUT /_search/pipeline/collapse_pipeline +{ + "response_processors": [ + { + "collapse" : { + "field": "color" + } + } + ] +} +``` + +### 使用搜索管道 + +在本例中,请求在按 `color` 字段折叠之前的前三个文档。由于前两个文档的 `color` 相同,第二个文档会被丢弃,因此请求返回第一个和第三个文档: + +```json +POST /my_index/_search?search_pipeline=collapse_pipeline +{ + "size": 3 +} +``` + +
+ + 响应 + + +```json +{ + "took" : 2, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 10, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "my_index", + "_id" : "1", + "_score" : 1.0, + "_source" : { + "title" : "document 1", + "color" : "blue" + } + }, + { + "_index" : "my_index", + "_id" : "3", + "_score" : 1.0, + "_source" : { + "title" : "document 3", + "color" : "red" + } + } + ] + }, + "profile" : { + "shards" : [ ] + } +} +``` +
diff --git a/i18n/zh/search-plugins/search-pipelines/creating-search-pipeline.md b/i18n/zh/search-plugins/search-pipelines/creating-search-pipeline.md new file mode 100644 index 00000000..f9f8c10a --- /dev/null +++ b/i18n/zh/search-plugins/search-pipelines/creating-search-pipeline.md @@ -0,0 +1,147 @@ +--- +title: 创建搜索管道 +--- + +# 创建搜索管道 + +搜索管道(Search Pipeline)存储在集群状态中。要创建搜索管道,必须在 OpenSearch 集群中配置一个有序的处理器列表。同一管道中可以包含多个相同类型的处理器。每个处理器都有一个 `tag` 标识符,用于将其与其他处理器区分开来。为特定处理器添加标签有助于调试错误消息,尤其是在添加了多个相同类型的处理器时。 + +#### 示例请求 + +以下请求创建一个搜索管道,其中包含一个 `filter_query` 请求处理器和一个响应处理器:前者使用 term 查询只返回公开消息,后者将字段 `message` 重命名为 `notification`: + +```json +PUT /_search/pipeline/my_pipeline +{ + "request_processors": [ + { + "filter_query" : { + "tag" : "tag1", + "description" : "This processor is going to restrict to publicly visible documents", + "query" : { + "term": { + "visibility": "public" + } + } + } + } + ], + "response_processors": [ + { + "rename_field": { + "field": "message", + "target_field": "notification" + } + } + ] +} +``` + +## 忽略处理器失败 + +默认情况下,如果搜索管道中的某个处理器失败,管道就会停止运行。如果希望在处理器失败时管道继续运行,可以在创建管道时将该处理器的 `ignore_failure` 参数设置为 `true`: + +```json +"filter_query" : { + "tag" : "tag1", + "description" : "This processor is going to restrict to publicly visible documents", + "ignore_failure": true, + "query" : { + "term": { + "visibility": "public" + } + } +} +``` + +如果该处理器失败,OpenSearch 会记录这次失败,并继续运行搜索管道中所有剩余的处理器。要检查是否发生过失败,可以使用[搜索管道指标](/search-plugins/search-pipelines/search-pipeline-metrics)。 + +## 更新搜索管道 + +要动态更新搜索管道,请使用 Search Pipeline API 替换该搜索管道。 + +#### 示例请求 {#example-request-1} + +以下示例请求通过添加一个 `filter_query` 请求处理器和一个 `rename_field` 响应处理器来更新插入(upsert)`my_pipeline`: + +```json +PUT /_search/pipeline/my_pipeline +{ + "request_processors": [ + { + "filter_query": { + "tag": "tag1", + "description": "This processor returns only publicly visible documents", + "query": { + "term": { + "visibility": "public" + } + } + } + } + ], + "response_processors": [ + { + "rename_field": { + "field": "message", + "target_field": "notification" + } + } + ] +} +``` + +## 搜索管道版本 + +创建管道时,可以在 `version` 参数中为其指定版本: + +```json +PUT _search/pipeline/my_pipeline +{ + "version": 1234, + "request_processors": [ + { + "script": { + "source": """ + if (ctx._source['size'] > 100) { + ctx._source['explain'] = false; + } + """ + } + } + ] +} +``` + +此后所有 `get pipeline` 请求的响应中都会提供该版本: + +```json +GET _search/pipeline/my_pipeline +``` + +响应中包含管道版本: + +
+ + 响应 + + +```json +{ + "my_pipeline": { + "version": 1234, + "request_processors": [ + { + "script": { + "source": """ + if (ctx._source['size'] > 100) { + ctx._source['explain'] = false; + } + """ + } + } + ] + } +} +``` +
diff --git a/i18n/zh/search-plugins/search-pipelines/filter-query-processor.md b/i18n/zh/search-plugins/search-pipelines/filter-query-processor.md new file mode 100644 index 00000000..aa94b5ad --- /dev/null +++ b/i18n/zh/search-plugins/search-pipelines/filter-query-processor.md @@ -0,0 +1,166 @@ +--- +title: Filter query +--- + +# Filter query 处理器 + +`filter_query` 搜索请求处理器会拦截搜索请求,并对请求附加一个额外的查询来过滤结果。当你不想改写应用中已有的查询,但又需要对结果进行额外过滤时,这个处理器非常有用。 + +## 请求字段 + +下表列出了所有可用的请求字段。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`query` | Object | 使用查询领域特定语言(DSL)编写的查询。有关 OpenSearch 查询类型的列表,请参阅 [Query DSL](/query-dsl/)。必需。 +`tag` | String | 处理器的标识符。可选。 +`description` | String | 处理器的描述。可选。 +`ignore_failure` | Boolean | 如果为 `true`,OpenSearch 会[忽略该处理器的任何失败](/search-plugins/search-pipelines/creating-search-pipeline#ignoring-processor-failures),并继续运行搜索管道中剩余的处理器。可选。默认值为 `false`。 + +## 示例 + +以下示例演示如何使用包含 `filter_query` 处理器的搜索管道。 + +### 准备工作 + +创建一个名为 `my_index` 的索引,并索引两个文档,一个公开,一个私有: + +```json +POST /my_index/_doc/1 +{ + "message": "This is a public message", + "visibility":"public" +} +``` + +```json +POST /my_index/_doc/2 +{ + "message": "This is a private message", + "visibility": "private" +} +``` + +### 创建搜索管道 + +以下请求创建一个名为 `my_pipeline` 的搜索管道,其中包含一个 `filter_query` 请求处理器,该处理器使用 term 查询只返回公开消息: + +```json +PUT /_search/pipeline/my_pipeline +{ + "request_processors": [ + { + "filter_query" : { + "tag" : "tag1", + "description" : "This processor is going to restrict to publicly visible documents", + "query" : { + "term": { + "visibility": "public" + } + } + } + } + ] +} +``` + +### 使用搜索管道 + +不使用搜索管道,在 `my_index` 中搜索文档: + +```json +GET /my_index/_search +``` + +响应包含两个文档: + +
+ + 响应 + + +```json +{ + "took" : 47, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 2, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "my_index", + "_id" : "1", + "_score" : 1.0, + "_source" : { + "message" : "This is a public message", + "visibility" : "public" + } + }, + { + "_index" : "my_index", + "_id" : "2", + "_score" : 1.0, + "_source" : { + "message" : "This is a private message", + "visibility" : "private" + } + } + ] + } +} +``` +
+ +要使用管道进行搜索,请在 `search_pipeline` 查询参数中指定管道名称: + +```json +GET /my_index/_search?search_pipeline=my_pipeline +``` + +响应只包含可见性为 `public` 的文档: + +
+ + 响应 + + +```json +{ + "took" : 19, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 0.0, + "hits" : [ + { + "_index" : "my_index", + "_id" : "1", + "_score" : 0.0, + "_source" : { + "message" : "This is a public message", + "visibility" : "public" + } + } + ] + } +} +``` +
diff --git a/i18n/zh/search-plugins/search-pipelines/index.md b/i18n/zh/search-plugins/search-pipelines/index.md new file mode 100644 index 00000000..9afbbb44 --- /dev/null +++ b/i18n/zh/search-plugins/search-pipelines/index.md @@ -0,0 +1,74 @@ +--- +title: 搜索管道 +--- + +# 搜索管道 + +你可以使用*搜索管道*(search pipeline)构建新的或复用已有的结果重排序器、查询改写器以及其他作用于查询或结果的组件。搜索管道让你更方便地在 OpenSearch 内部处理搜索查询和搜索结果。将部分应用功能迁移到 OpenSearch 搜索管道中,可以降低应用的整体复杂度。在搜索管道中,你需要指定一个处理器(processor)列表,由这些处理器执行模块化的任务。之后,你可以轻松地添加处理器或调整处理器顺序,为应用定制搜索结果。 + +## 术语 + +以下是搜索管道相关术语列表: + +* [*搜索请求处理器*](/search-plugins/search-pipelines/search-processors#search-request-processors)(search request processor):拦截搜索请求(请求中传递的查询和元数据),使用或针对该搜索请求执行操作,然后返回搜索请求的组件。 +* [*搜索响应处理器*](/search-plugins/search-pipelines/search-processors#search-response-processors)(search response processor):拦截搜索响应和搜索请求(请求中传递的查询、结果和元数据),使用或针对该搜索响应执行操作,然后返回搜索响应的组件。 +* [*搜索阶段结果处理器*](/search-plugins/search-pipelines/search-processors#search-phase-results-processors)(search phase results processor):在协调节点层面、于各搜索阶段之间运行的组件。搜索阶段结果处理器会拦截某一搜索阶段检索到的结果,对其进行转换后再传递给下一个搜索阶段。 +* [*处理器*](/search-plugins/search-pipelines/search-processors):搜索请求处理器或搜索响应处理器。 +* *搜索管道*:集成在 OpenSearch 中的有序处理器列表。管道会拦截查询、对查询进行处理、将其发送给 OpenSearch、拦截结果、对结果进行处理,然后将结果返回给调用方应用,如下图所示。 + +![搜索处理器示意图](/images/search-pipelines.png) + +::: info 注意 +管道的请求处理和响应处理都在协调节点上执行,因此不存在分片级别的处理。 +::: + +## 处理器 + +要详细了解可用的搜索处理器,请参阅[搜索处理器](/search-plugins/search-pipelines/search-processors)。 + +## 示例 + +要创建搜索管道,请向搜索管道端点发送请求,并指定一个有序的处理器列表,这些处理器将按顺序依次应用: + +```json +PUT /_search/pipeline/my_pipeline +{ + "request_processors": [ + { + "filter_query" : { + "tag" : "tag1", + "description" : "This processor is going to restrict to publicly visible documents", + "query" : { + "term": { + "visibility": "public" + } + } + } + } + ], + "response_processors": [ + { + "rename_field": { + "field": "message", + "target_field": "notification" + } + } + ] +} +``` + +有关创建和更新搜索管道的更多信息,请参阅[创建搜索管道](/search-plugins/search-pipelines/creating-search-pipeline)。 + +要在查询中使用管道,请在 `search_pipeline` 查询参数中指定管道名称: + +```json +GET /my_index/_search?search_pipeline=my_pipeline +``` + +此外,你也可以在请求中使用临时管道,或者为索引设置默认管道。要了解更多信息,请参阅[使用搜索管道](/search-plugins/search-pipelines/using-search-pipeline)。 + +要了解如何获取现有搜索管道的详细信息,请参阅[获取搜索管道](/search-plugins/search-pipelines/retrieving-search-pipeline)。 + +## 搜索管道指标 + +有关获取搜索管道统计信息的内容,请参阅[搜索管道指标](/search-plugins/search-pipelines/search-pipeline-metrics)。 diff --git a/i18n/zh/search-plugins/search-pipelines/neural-query-enricher.md b/i18n/zh/search-plugins/search-pipelines/neural-query-enricher.md new file mode 100644 index 00000000..44322194 --- /dev/null +++ b/i18n/zh/search-plugins/search-pipelines/neural-query-enricher.md @@ -0,0 +1,41 @@ +--- +title: Neural query enricher +--- + +# Neural query enricher 处理器 + +`neural_query_enricher` 搜索请求处理器用于在索引级别或字段级别为[神经搜索](/search-plugins/neural-search)(Neural Search)查询设置默认的机器学习(ML)模型 ID。要了解有关 ML 模型的更多信息,请参阅[在 OpenSearch 中使用 ML 模型](/ml-commons-plugin/using-ml-models)和[连接远程模型](/ml-commons-plugin/remote-models/)。 + +## 请求字段 + +下表列出了所有可用的请求字段。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`default_model_id` | String | 索引默认模型的模型 ID。可选。`default_model_id` 和 `neural_field_default_id` 至少要指定一个。如果两者都提供,则以 `neural_field_default_id` 为准。 +`neural_field_default_id` | Object | 由键值对组成的映射,表示文档字段名称及其关联的默认模型 ID。可选。`default_model_id` 和 `neural_field_default_id` 至少要指定一个。如果两者都提供,则以 `neural_field_default_id` 为准。 +`tag` | String | 处理器的标识符。可选。 +`description` | String | 处理器的描述。可选。 + +## 示例 + +以下示例请求创建一个包含 `neural_query_enricher` 搜索请求处理器的搜索管道。该处理器在索引级别设置默认模型 ID,并为索引中的两个特定字段分别提供不同的默认模型 ID: + +```json +PUT /_search/pipeline/default_model_pipeline +{ + "request_processors": [ + { + "neural_query_enricher" : { + "tag": "tag1", + "description": "Sets the default model ID at index and field levels", + "default_model_id": "u5j0qYoBMtvQlfhaxOsa", + "neural_field_default_id": { + "my_field_1": "uZj0qYoBMtvQlfhaYeud", + "my_field_2": "upj0qYoBMtvQlfhaZOuM" + } + } + } + ] +} +``` diff --git a/i18n/zh/search-plugins/search-pipelines/normalization-processor.md b/i18n/zh/search-plugins/search-pipelines/normalization-processor.md new file mode 100644 index 00000000..f2484aec --- /dev/null +++ b/i18n/zh/search-plugins/search-pipelines/normalization-processor.md @@ -0,0 +1,112 @@ +--- +title: Normalization +--- + +# Normalization 处理器 + +`normalization-processor` 是一个搜索阶段结果处理器(search phase results processor),在搜索执行的查询阶段和获取阶段之间运行。它会拦截查询阶段的结果,对来自不同查询子句的文档评分进行归一化(normalization)和组合(combination),然后再将文档传递给获取阶段。 + +## 评分归一化与组合 + +许多应用既需要关键词匹配,也需要语义理解。例如,对于包含关键词的查询,BM25 能准确地提供相关的搜索结果;而当查询需要理解自然语言时,神经网络的表现更好。因此,你可能希望将 BM25 的搜索结果与 k-NN 搜索或神经搜索(Neural Search)的结果组合起来。然而,BM25 和 k-NN 搜索在计算匹配文档的相关性评分(Relevance Score)时使用的尺度不同。实验数据表明,在组合多个查询的评分之前,先对它们进行归一化,使其处于同一尺度上,会带来好处。有关评分归一化与组合的延伸阅读(包括基准测试和各种方法),请参阅[这篇语义搜索博客文章](https://opensearch.org/blog/semantic-science-benchmarks/)。 + +## 先查询后获取 + +OpenSearch 支持两种搜索类型:`query_then_fetch` 和 `dfs_query_then_fetch`。下图概述了包含归一化处理器的“先查询后获取”(query-then-fetch)流程。 + +![归一化处理器流程图](/images/normalization-processor.png) + +当你向某个节点发送搜索请求时,该节点就成为*协调节点*(coordinating node)。在搜索的第一个阶段,即*查询阶段*(query phase),协调节点将搜索请求路由到索引中的所有分片(Shard),包括主分片和副本分片。随后,每个分片在本地运行搜索查询,并返回匹配文档的元数据,其中包括文档 ID 和相关性评分。接着,`normalization-processor` 对来自不同查询子句的评分进行归一化和组合。协调节点合并各分片的本地结果列表并排序,汇总出与查询匹配的全局排名靠前文档列表。之后,搜索执行进入*获取阶段*(fetch phase),协调节点向全局列表中各文档所在的分片请求这些文档。每个分片将文档的 `_source` 返回给协调节点。最后,协调节点将包含结果的搜索响应发送给你。 + +## 请求字段 + +下表列出了所有可用的请求字段。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`normalization.technique` | String | 评分归一化方法。有效值为 [`min_max`](https://en.wikipedia.org/wiki/Feature_scaling#Rescaling_(min-max_normalization)) 和 [`l2`](https://en.wikipedia.org/wiki/Cosine_similarity#L2-normalized_Euclidean_distance)。可选。默认值为 `min_max`。 +`combination.technique` | String | 评分组合方法。有效值为 [`arithmetic_mean`](https://en.wikipedia.org/wiki/Arithmetic_mean)、[`geometric_mean`](https://en.wikipedia.org/wiki/Geometric_mean) 和 [`harmonic_mean`](https://en.wikipedia.org/wiki/Harmonic_mean)。可选。默认值为 `arithmetic_mean`。 +`combination.parameters.weights` | Array of floating-point values | 指定每个查询使用的权重。有效值在 [0.0, 1.0] 范围内,表示小数形式的百分比。权重越接近 1.0,查询所占的权重越大。`weights` 数组中值的数量必须等于查询的数量,数组中各值之和必须等于 1.0。可选。如果未提供,则所有查询的权重相同。 +`tag` | String | 处理器的标识符。可选。 +`description` | String | 处理器的描述。可选。 +`ignore_failure` | Boolean | 对于此处理器,该值会被忽略。如果处理器失败,管道总是会失败并返回错误。 + +## 示例 + +以下示例演示如何使用包含 `normalization-processor` 的搜索管道。 + +有关完整示例,请参阅[神经搜索教程](/search-plugins/neural-search-tutorial#tutorial)。 + +### 创建搜索管道 + +以下请求创建一个包含 `normalization-processor` 的搜索管道,该处理器使用 `min_max` 归一化方法和 `arithmetic_mean` 组合方法: + +```json +PUT /_search/pipeline/nlp-search-pipeline +{ + "description": "Post processor for hybrid search", + "phase_results_processors": [ + { + "normalization-processor": { + "normalization": { + "technique": "min_max" + }, + "combination": { + "technique": "arithmetic_mean", + "parameters": { + "weights": [ + 0.3, + 0.7 + ] + } + } + } + } + ] +} +``` + +### 使用搜索管道 + +在 `hybrid` 查询中提供要组合的查询子句,并应用上一节创建的搜索管道,使评分按所选方法进行组合: + +```json +GET /my-nlp-index/_search?search_pipeline=nlp-search-pipeline +{ + "_source": { + "exclude": [ + "passage_embedding" + ] + }, + "query": { + "hybrid": { + "queries": [ + { + "match": { + "text": { + "query": "horse" + } + } + }, + { + "neural": { + "passage_embedding": { + "query_text": "wild west", + "model_id": "aVeif4oB5Vm0Tdw8zYO2", + "k": 5 + } + } + } + ] + } + } +} +``` + +有关设置混合搜索的更多信息,请参阅[使用混合搜索](/search-plugins/hybrid-search#using-hybrid-search)。 + +## 搜索调优建议 + +为了提高搜索相关性,我们建议增大样本量。 + +如果混合查询没有返回某些预期的结果,可能是因为子查询返回的文档太少。`normalization-processor` 只转换每个子查询返回的结果,不会执行任何额外的采样。在实验中,我们使用 [nDCG@10](https://en.wikipedia.org/wiki/Discounted_cumulative_gain) 来衡量信息检索质量随返回文档数量(size)的变化。我们发现,对于最多包含 1000 万个文档的数据集,size 在 [100, 200] 范围内效果最佳。我们不建议将 size 增大到超出推荐值,因为更大的 size 值并不会提高搜索相关性,反而会增加搜索延迟。 diff --git a/i18n/zh/search-plugins/search-pipelines/oversample-processor.md b/i18n/zh/search-plugins/search-pipelines/oversample-processor.md new file mode 100644 index 00000000..86573129 --- /dev/null +++ b/i18n/zh/search-plugins/search-pipelines/oversample-processor.md @@ -0,0 +1,280 @@ +--- +title: Oversample +--- + +# Oversample 处理器 + +`oversample` 请求处理器将搜索请求的 `size` 参数乘以指定的 `sample_factor`(>= 1.0),并将原始值保存在 `original_size` 管道变量中。`oversample` 处理器设计用于配合 [`truncate_hits` 响应处理器](/search-plugins/search-pipelines/truncate-hits-processor)使用,但也可以单独使用。 + +## 请求字段 + +下表列出了所有请求字段。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`sample_factor` | Float | 在处理搜索请求之前应用于 `size` 参数的乘数因子(>= 1.0)。必需。 +`context_prefix` | String | 可用于限定 `original_size` 变量的作用域,以避免冲突。可选。 +`tag` | String | 处理器的标识符。可选。 +`description` | String | 处理器的描述。可选。 +`ignore_failure` | Boolean | 如果为 `true`,OpenSearch 会[忽略该处理器的任何失败](/search-plugins/search-pipelines/creating-search-pipeline#ignoring-processor-failures),并继续运行搜索管道中剩余的处理器。可选。默认值为 `false`。 + +## 示例 + +以下示例演示如何使用包含 `oversample` 处理器的搜索管道。 + +### 准备工作 + +创建一个名为 `my_index` 的索引,其中包含多个文档: + +```json +POST /_bulk +{ "create":{"_index":"my_index","_id":1}} +{ "doc": { "title" : "document 1" }} +{ "create":{"_index":"my_index","_id":2}} +{ "doc": { "title" : "document 2" }} +{ "create":{"_index":"my_index","_id":3}} +{ "doc": { "title" : "document 3" }} +{ "create":{"_index":"my_index","_id":4}} +{ "doc": { "title" : "document 4" }} +{ "create":{"_index":"my_index","_id":5}} +{ "doc": { "title" : "document 5" }} +{ "create":{"_index":"my_index","_id":6}} +{ "doc": { "title" : "document 6" }} +{ "create":{"_index":"my_index","_id":7}} +{ "doc": { "title" : "document 7" }} +{ "create":{"_index":"my_index","_id":8}} +{ "doc": { "title" : "document 8" }} +{ "create":{"_index":"my_index","_id":9}} +{ "doc": { "title" : "document 9" }} +{ "create":{"_index":"my_index","_id":10}} +{ "doc": { "title" : "document 10" }} +``` + +### 创建搜索管道 + +以下请求创建一个名为 `my_pipeline` 的搜索管道,其中包含一个 `oversample` 请求处理器,该处理器请求的命中数比 `size` 中指定的多 50%: + +```json +PUT /_search/pipeline/my_pipeline +{ + "request_processors": [ + { + "oversample" : { + "tag" : "oversample_1", + "description" : "This processor will multiply `size` by 1.5.", + "sample_factor" : 1.5 + } + } + ] +} +``` + +### 使用搜索管道 + +不使用搜索管道,在 `my_index` 中搜索文档: + +```json +POST /my_index/_search +{ + "size": 5 +} +``` + +响应包含五个命中: + +
+ + 响应 + + +```json +{ + "took" : 3, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 10, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "my_index", + "_id" : "1", + "_score" : 1.0, + "_source" : { + "doc" : { + "title" : "document 1" + } + } + }, + { + "_index" : "my_index", + "_id" : "2", + "_score" : 1.0, + "_source" : { + "doc" : { + "title" : "document 2" + } + } + }, + { + "_index" : "my_index", + "_id" : "3", + "_score" : 1.0, + "_source" : { + "doc" : { + "title" : "document 3" + } + } + }, + { + "_index" : "my_index", + "_id" : "4", + "_score" : 1.0, + "_source" : { + "doc" : { + "title" : "document 4" + } + } + }, + { + "_index" : "my_index", + "_id" : "5", + "_score" : 1.0, + "_source" : { + "doc" : { + "title" : "document 5" + } + } + } + ] + } +} +``` +
+ +要使用管道进行搜索,请在 `search_pipeline` 查询参数中指定管道名称: + +```json +POST /my_index/_search?search_pipeline=my_pipeline +{ + "size": 5 +} +``` + +响应包含 8 个文档(5 * 1.5 = 7.5,向上取整为 8): + +
+ + 响应 + + +```json +{ + "took" : 13, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 10, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "my_index", + "_id" : "1", + "_score" : 1.0, + "_source" : { + "doc" : { + "title" : "document 1" + } + } + }, + { + "_index" : "my_index", + "_id" : "2", + "_score" : 1.0, + "_source" : { + "doc" : { + "title" : "document 2" + } + } + }, + { + "_index" : "my_index", + "_id" : "3", + "_score" : 1.0, + "_source" : { + "doc" : { + "title" : "document 3" + } + } + }, + { + "_index" : "my_index", + "_id" : "4", + "_score" : 1.0, + "_source" : { + "doc" : { + "title" : "document 4" + } + } + }, + { + "_index" : "my_index", + "_id" : "5", + "_score" : 1.0, + "_source" : { + "doc" : { + "title" : "document 5" + } + } + }, + { + "_index" : "my_index", + "_id" : "6", + "_score" : 1.0, + "_source" : { + "doc" : { + "title" : "document 6" + } + } + }, + { + "_index" : "my_index", + "_id" : "7", + "_score" : 1.0, + "_source" : { + "doc" : { + "title" : "document 7" + } + } + }, + { + "_index" : "my_index", + "_id" : "8", + "_score" : 1.0, + "_source" : { + "doc" : { + "title" : "document 8" + } + } + } + ] + } +} +``` +
diff --git a/i18n/zh/search-plugins/search-pipelines/personalize-search-ranking.md b/i18n/zh/search-plugins/search-pipelines/personalize-search-ranking.md new file mode 100644 index 00000000..0af7c543 --- /dev/null +++ b/i18n/zh/search-plugins/search-pipelines/personalize-search-ranking.md @@ -0,0 +1,78 @@ +--- +title: Personalize search ranking +--- + +# Personalize search ranking 处理器 + +`personalize_search_ranking` 搜索响应处理器会拦截搜索响应,并使用 [Amazon Personalize](https://aws.amazon.com/personalize/) 按照 Amazon Personalize 的排名对搜索结果进行重排序(reranking)。该排名基于用户过去的行为,以及有关搜索条目和用户的元数据。 + +::: warning 重要 +要使用 `personalize_search_ranking` 处理器,必须先安装 Amazon Personalize Search Ranking(`opensearch-search-processor`)插件。有关详细说明,请参阅[安装和配置 Amazon Personalize Search Ranking 插件](https://docs.aws.amazon.com/personalize/latest/dg/opensearch-install.html)。 +::: + +## 请求字段 + +下表列出了所有可用的请求字段。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`campaign_arn` | String | 用于个性化结果的 Amazon Personalize 活动(campaign)的 Amazon 资源名称(ARN)。必需。 +`recipe` | String | 要使用的 Amazon Personalize 配方(recipe)名称。目前该字段唯一支持的值为 `aws-personalized-ranking`。必需。 +`weight` | Float | 用于 OpenSearch 和 Amazon Personalize 所提供排名的权重。有效值在 [0.0, 1.0] 范围内。权重越接近 1.0,计算排名时 Amazon Personalize 相对于 OpenSearch 所占的权重越大。如果指定 0.0,则使用 OpenSearch 的排名;如果指定 1.0,则使用 Amazon Personalize 的排名。必需。 +`item_id_field` | String | 如果 OpenSearch 中已索引文档的 `_id` 字段与你的 Amazon Personalize `itemId` 不对应,请指定与之对应的字段名称。默认情况下,插件假定 `_id` 数据与 Amazon Personalize 数据中的 `itemId` 相匹配。 +`iam_role_arn` | String | 如果你使用多个角色来限制组织中不同用户组的权限,请指定有权访问 Amazon Personalize 的角色的 ARN。如果只使用 OpenSearch 密钥库中的 AWS 凭证,则可以省略此字段。可选。 +`tag` | String | 处理器的标识符。可选。 +`description` | String | 处理器的描述。可选。 +`ignore_failure` | Boolean | 如果为 `true`,OpenSearch 会[忽略该处理器的任何失败](/search-plugins/search-pipelines/creating-search-pipeline#ignoring-processor-failures),并继续运行搜索管道中剩余的处理器。可选。默认值为 `false`。 + +## 示例 + +以下示例演示如何使用包含 `personalize_search_ranking` 处理器的搜索管道。 + +### 创建搜索管道 + +以下请求创建一个包含 `personalize_search_ranking` 响应处理器的搜索管道: + +```json +PUT /_search/pipeline/my-pipeline +{ + "description": "A pipeline to apply custom reranking from Amazon Personalize", + "response_processors" : [ + { + "personalized_search_ranking" : { + "campaign_arn" : "Amazon Personalize Campaign ARN", + "item_id_field" : "productId", + "recipe" : "aws-personalized-ranking", + "weight" : "0.3", + "tag" : "personalize-processor", + "iam_role_arn": "Role ARN", + "aws_region": "AWS region" + } + } + ] +} +``` + +### 使用搜索管道 + +要使用管道进行搜索,请在 `search_pipeline` 查询参数中指定管道名称。例如,以下请求使用上一节设置的管道搜索喜剧: + +```json +GET /movies/_search?search_pipeline=my-pipeline +{ + "query": { + "multi_match": { + "query": "Comedy", + "fields": ["GENRES"] + } + }, + "ext": { + "personalize_request_parameters": { + "user_id": "user ID", + "context": { "DEVICE" : "mobile phone" } + } + } +} +``` + +有关更多详细信息,请参阅[对来自 OpenSearch(自行管理)的搜索结果进行个性化](https://docs.aws.amazon.com/personalize/latest/dg/personalize-opensearch.html)。 diff --git a/i18n/zh/search-plugins/search-pipelines/rag-processor.md b/i18n/zh/search-plugins/search-pipelines/rag-processor.md new file mode 100644 index 00000000..ef1f3d6f --- /dev/null +++ b/i18n/zh/search-plugins/search-pipelines/rag-processor.md @@ -0,0 +1,94 @@ +--- +title: 检索增强生成 +--- + +# 检索增强生成处理器 + +`retrieval_augmented_generation` 处理器是一个搜索结果处理器,可以在[对话式搜索](/search-plugins/conversational-search)(conversational search)中用于检索增强生成(retrieval-augmented generation,RAG)。该处理器会拦截查询结果,从对话记忆中检索该对话之前的消息,并向大语言模型(LLM)发送提示词。处理器收到 LLM 的响应后,会将响应保存到对话记忆中,并同时返回原始的 OpenSearch 查询结果和 LLM 响应。 + +::: info 注意 +截至 OpenSearch 2.12,`retrieval_augmented_generation` 处理器仅支持 OpenAI 和 Amazon Bedrock 模型。 +::: + +## 请求字段 + +下表列出了所有可用的请求字段。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`model_id` | String | 管道中使用的模型的 ID。必需。 +`context_field_list` | Array | 文档 source 中所包含字段的列表,管道将这些字段用作 RAG 的上下文。必需。有关更多信息,请参阅[上下文字段列表](#context-field-list)。 +`system_prompt` | String | 发送给 LLM 的系统提示词,用于调整其行为,例如回答的语气。可以是角色设定描述或一组指令。可选。 +`user_instructions` | String | 发送给 LLM 的人工编写的指令,用于引导其生成结果。 +`tag` | String | 处理器的标识符。可选。 +`description` | String | 处理器的描述。可选。 + +### 上下文字段列表 + +`context_field_list` 是文档 source 中所包含字段的列表,管道将这些字段用作 RAG 的上下文。例如,假设你的 OpenSearch 索引包含一组文档,每个文档都有 `title` 和 `text`: + +```json +{ + "_index": "qa_demo", + "_id": "SimKcIoBOVKVCYpk1IL-", + "_source": { + "title": "Abraham Lincoln 2", + "text": "Abraham Lincoln was born on February 12, 1809, the second child of Thomas Lincoln and Nancy Hanks Lincoln, in a log cabin on Sinking Spring Farm near Hodgenville, Kentucky.[2] He was a descendant of Samuel Lincoln, an Englishman who migrated from Hingham, Norfolk, to its namesake, Hingham, Massachusetts, in 1638. The family then migrated west, passing through New Jersey, Pennsylvania, and Virginia.[3] Lincoln was also a descendant of the Harrison family of Virginia; his paternal grandfather and namesake, Captain Abraham Lincoln and wife Bathsheba (née Herring) moved the family from Virginia to Jefferson County, Kentucky.[b] The captain was killed in an Indian raid in 1786.[5] His children, including eight-year-old Thomas, Abraham's father, witnessed the attack.[6][c] Thomas then worked at odd jobs in Kentucky and Tennessee before the family settled in Hardin County, Kentucky, in the early 1800s.[6]\n" + } +} +``` + +可以在处理器中设置 `"context_field_list": ["text"]`,指定只将 `text` 的内容发送给 LLM。 + +## 示例 + +以下示例演示如何使用包含 `retrieval_augmented_generation` 处理器的搜索管道。 + +### 创建搜索管道 + +以下请求为 OpenAI 模型创建一个包含 `retrieval_augmented_generation` 处理器的搜索管道: + +```json +PUT /_search/pipeline/rag_pipeline +{ + "response_processors": [ + { + "retrieval_augmented_generation": { + "tag": "openai_pipeline_demo", + "description": "Demo pipeline Using OpenAI Connector", + "model_id": "gnDIbI0BfUsSoeNT_jAw", + "context_field_list": ["text"], + "system_prompt": "You are a helpful assistant", + "user_instructions": "Generate a concise and informative answer in less than 100 words for the given question" + } + } + ] +} +``` + +### 使用搜索管道 + +将 OpenSearch 查询与一个 `ext` 对象组合使用,该对象存储了供 LLM 使用的生成式问答参数: + +```json +GET /my_rag_test_data/_search?search_pipeline=rag_pipeline +{ + "query": { + "match": { + "text": "Abraham Lincoln" + } + }, + "ext": { + "generative_qa_parameters": { + "llm_model": "gpt-3.5-turbo", + "llm_question": "Was Abraham Lincoln a good politician", + "memory_id": "iXC4bI0BfUsSoeNTjS30", + "context_size": 5, + "message_size": 5, + "timeout": 15 + } + } +} +``` + +有关设置对话式搜索的更多信息,请参阅[使用对话式搜索](/search-plugins/conversational-search#using-conversational-search)。 diff --git a/i18n/zh/search-plugins/search-pipelines/rename-field-processor.md b/i18n/zh/search-plugins/search-pipelines/rename-field-processor.md new file mode 100644 index 00000000..624096d7 --- /dev/null +++ b/i18n/zh/search-plugins/search-pipelines/rename-field-processor.md @@ -0,0 +1,202 @@ +--- +title: Rename field +--- + +# Rename field 处理器 + +`rename_field` 搜索响应处理器会拦截搜索响应并重命名指定的字段。当索引和应用对同一字段使用不同名称时,这个处理器非常有用。例如,如果你在索引中重命名了某个字段,`rename_field` 处理器可以在将响应发送给应用之前,把新名称改回旧名称。 + +## 请求字段 + +下表列出了所有可用的请求字段。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`field` | String | 要重命名的字段。必需。 +`target_field` | String | 新的字段名称。必需。 +`tag` | String | 处理器的标识符。 +`description` | String | 处理器的描述。 +`ignore_failure` | Boolean | 如果为 `true`,OpenSearch 会[忽略该处理器的任何失败](/search-plugins/search-pipelines/creating-search-pipeline#ignoring-processor-failures),并继续运行搜索管道中剩余的处理器。可选。默认值为 `false`。 + +## 示例 + +以下示例演示如何使用包含 `rename_field` 处理器的搜索管道。 + +### 准备工作 + +创建一个名为 `my_index` 的索引,并索引一个包含 `message` 字段的文档: + +```json +POST /my_index/_doc/1 +{ + "message": "This is a public message", + "visibility":"public" +} +``` + +### 创建搜索管道 + +以下请求创建一个包含 `rename_field` 响应处理器的搜索管道,该处理器将字段 `message` 重命名为 `notification`: + +```json +PUT /_search/pipeline/my_pipeline +{ + "response_processors": [ + { + "rename_field": { + "field": "message", + "target_field": "notification" + } + } + ] +} +``` + +### 使用搜索管道 + +不使用搜索管道,在 `my_index` 中搜索文档: + +```json +GET /my_index/_search +``` + +响应包含字段 `message`: + +
+ + 响应 + + +```json +{ + "took" : 1, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 2, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "my_index", + "_id" : "1", + "_score" : 1.0, + "_source" : { + "message" : "This is a public message", + "visibility" : "public" + } + } + ] + } +} +``` +
+ +要使用管道进行搜索,请在 `search_pipeline` 查询参数中指定管道名称: + +```json +GET /my_index/_search?search_pipeline=my_pipeline +``` + +`message` 字段已被重命名为 `notification`: + +
+ + 响应 + + +```json +{ + "took" : 2, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 0.0, + "hits" : [ + { + "_index" : "my_index", + "_id" : "1", + "_score" : 0.0, + "_source" : { + "visibility" : "public", + "notification" : "This is a public message" + } + } + ] + } +} +``` +
+ +也可以使用 `fields` 选项搜索文档中的特定字段: + +```json +POST /my_index/_search?pretty&search_pipeline=my_pipeline +{ + "fields":["visibility", "message"] +} +``` + +在响应中,字段 `message` 已被重命名为 `notification`: + +
+ + 响应 + + +```json +{ + "took" : 4, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 0.0, + "hits" : [ + { + "_index" : "my_index", + "_id" : "1", + "_score" : 0.0, + "_source" : { + "visibility" : "public", + "notification" : "This is a public message" + }, + "fields" : { + "visibility" : [ + "public" + ], + "notification" : [ + "This is a public message" + ] + } + } + ] + } +} + +``` +
diff --git a/i18n/zh/search-plugins/search-pipelines/rerank-processor.md b/i18n/zh/search-plugins/search-pipelines/rerank-processor.md new file mode 100644 index 00000000..aa43f953 --- /dev/null +++ b/i18n/zh/search-plugins/search-pipelines/rerank-processor.md @@ -0,0 +1,108 @@ +--- +title: Rerank +--- + +# Rerank 处理器 + +`rerank` 搜索请求处理器会拦截搜索结果,并将其传递给交叉编码器(cross-encoder)模型进行重排序(reranking)。模型会结合评分上下文对结果重新排序,然后处理器根据文档的新评分对搜索结果中的文档进行排序。 + +## 请求字段 + +下表列出了所有可用的请求字段。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`` | Object | 重排序器类型,为 rerank 处理器提供所有重排序调用都需要的静态信息。必需。 +`context` | Object | 为 rerank 处理器提供在查询时生成重排序上下文所需的信息。 +`tag` | String | 处理器的标识符。可选。 +`description` | String | 处理器的描述。可选。 +`ignore_failure` | Boolean | 如果为 `true`,OpenSearch 会[忽略该处理器的任何失败](/search-plugins/search-pipelines/creating-search-pipeline#ignoring-processor-failures),并继续运行搜索管道中剩余的处理器。可选。默认值为 `false`。 + +### `ml_opensearch` 重排序器类型 {#the-mlopensearch-reranker-type} + +`ml_opensearch` 重排序器类型设计用于配合 OpenSearch 提供的交叉编码器模型使用。对于这种重排序器类型,请指定以下字段。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`ml_opensearch` | Object | 为 rerank 处理器提供模型信息。必需。 +`ml_opensearch.model_id` | String | 交叉编码器模型的模型 ID。必需。有关更多信息,请参阅[使用 ML 模型](/ml-commons-plugin/using-ml-models)。 +`context.document_fields` | Array | 文档字段数组,指定从哪些字段中检索交叉编码器模型所需的上下文。必需。 + +## 示例 + +以下示例演示如何使用包含 `rerank` 处理器的搜索管道。 + +### 创建搜索管道 + +以下请求创建一个包含 `rerank` 响应处理器的搜索管道: + +```json +PUT /_search/pipeline/rerank_pipeline +{ + "response_processors": [ + { + "rerank": { + "ml_opensearch": { + "model_id": "gnDIbI0BfUsSoeNT_jAw" + }, + "context": { + "document_fields": [ "title", "text_representation"] + } + } + } + ] +} +``` + +### 使用搜索管道 + +将 OpenSearch 查询与一个 `ext` 对象组合使用,该对象包含供大语言模型(LLM)使用的查询上下文。提供用于对结果进行重排序的 `query_text`: + +```json +POST /_search?search_pipeline=rerank_pipeline +{ + "query": { + "match": { + "text_representation": "Where is Albuquerque?" + } + }, + "ext": { + "rerank": { + "query_context": { + "query_text": "Where is Albuquerque?" + } + } + } +} +``` + +除了指定 `query_text`,也可以提供包含重排序所用文本的字段的完整路径。例如,如果在 `text_representation` 对象中指定了子字段 `query`,请在 `query_text_path` 参数中指定其路径: + +```json +POST /_search?search_pipeline=rerank_pipeline +{ + "query": { + "match": { + "text_representation": { + "query": "Where is Albuquerque?" + } + } + }, + "ext": { + "rerank": { + "query_context": { + "query_text_path": "query.match.text_representation.query" + } + } + } +} +``` + +`query_context` 对象包含以下字段。 + +字段名称 | 描述 +:--- | :--- +`query_text` | 用于对搜索结果进行重排序的问题的自然语言文本。`query_text` 和 `query_text_path` 必须指定其中一个(不能同时指定)。 +`query_text_path` | 用于对搜索结果进行重排序的问题文本的完整 JSON 路径。`query_text` 和 `query_text_path` 必须指定其中一个(不能同时指定)。路径的最大字符数为 `1000`。 + +有关设置重排序的更多信息,请参阅[对搜索结果进行重排序](/search-plugins/search-relevance/reranking-search-results)。 diff --git a/i18n/zh/search-plugins/search-pipelines/retrieving-search-pipeline.md b/i18n/zh/search-plugins/search-pipelines/retrieving-search-pipeline.md new file mode 100644 index 00000000..748c89b8 --- /dev/null +++ b/i18n/zh/search-plugins/search-pipelines/retrieving-search-pipeline.md @@ -0,0 +1,52 @@ +--- +title: 获取搜索管道 +--- + +# 获取搜索管道 + +要获取现有搜索管道的详细信息,请使用 Search Pipeline API。 + +要查看所有搜索管道,请使用以下请求: + +```json +GET /_search/pipeline +``` + +响应包含你在上一节中设置的管道: +
+ + 响应 + + +```json +{ + "my_pipeline" : { + "request_processors" : [ + { + "filter_query" : { + "tag" : "tag1", + "description" : "This processor is going to restrict to publicly visible documents", + "query" : { + "term" : { + "visibility" : "public" + } + } + } + } + ] + } +} +``` +
+ +要查看特定管道,请将管道名称指定为路径参数: + +```json +GET /_search/pipeline/my_pipeline +``` + +也可以使用通配符模式查看部分管道,例如: + +```json +GET /_search/pipeline/my* +``` diff --git a/i18n/zh/search-plugins/search-pipelines/script-processor.md b/i18n/zh/search-plugins/search-pipelines/script-processor.md new file mode 100644 index 00000000..9fb00d93 --- /dev/null +++ b/i18n/zh/search-plugins/search-pipelines/script-processor.md @@ -0,0 +1,51 @@ +--- +title: Script +--- + +# Script 处理器 + +`script` 搜索请求处理器会拦截搜索请求,并添加一个对传入请求运行的内联 Painless 脚本。该脚本只能作用于以下请求字段: + +- `from` +- `size` +- `explain` +- `version` +- `seq_no_primary_term` +- `track_scores` +- `track_total_hits` +- `min_score` +- `terminate_after` +- `profile` + +有关请求字段的定义,请参阅[搜索请求字段](/api-reference/search#request-body)。 + +## 请求字段 + +下表列出了所有可用的请求字段。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`source` | Inline script | 要运行的脚本。必需。 +`lang` | String | 脚本语言。可选。仅支持 `painless`。 +`tag` | String | 处理器的标识符。可选。 +`description` | String | 处理器的描述。可选。 +`ignore_failure` | Boolean | 如果为 `true`,OpenSearch 会[忽略该处理器的任何失败](/search-plugins/search-pipelines/creating-search-pipeline#ignoring-processor-failures),并继续运行搜索管道中剩余的处理器。可选。默认值为 `false`。 + +## 示例 + +以下请求创建一个包含 `script` 请求处理器的搜索管道。由于 `explain` 是一项开销很大的操作,该脚本将评分解释限制为只针对一个文档: + +```json +PUT /_search/pipeline/explain_one_result +{ + "description": "A pipeline to limit the explain operation to one result only", + "request_processors": [ + { + "script": { + "lang": "painless", + "source": "if (ctx._source['size'] > 1) { ctx._source['explain'] = false } else { ctx._source['explain'] = true }" + } + } + ] +} +``` diff --git a/i18n/zh/search-plugins/search-pipelines/search-pipeline-metrics.md b/i18n/zh/search-plugins/search-pipelines/search-pipeline-metrics.md new file mode 100644 index 00000000..128ca7d5 --- /dev/null +++ b/i18n/zh/search-plugins/search-pipelines/search-pipeline-metrics.md @@ -0,0 +1,162 @@ +--- +title: 搜索管道指标 +--- + +# 搜索管道指标 + +要查看搜索管道指标,请使用 [Nodes Stats API](/api-reference/nodes-apis/nodes-stats): + +```json +GET /_nodes/stats/search_pipeline +``` + +响应包含所有搜索管道的统计信息: + +```json +{ + "_nodes" : { + "total" : 1, + "successful" : 1, + "failed" : 0 + }, + "cluster_name" : "runTask", + "nodes" : { + "CpvTK7KuRD6Oww8TTp8g2Q" : { + "timestamp" : 1689007282929, + "name" : "runTask-0", + "transport_address" : "127.0.0.1:9300", + "host" : "127.0.0.1", + "ip" : "127.0.0.1:9300", + "roles" : [ + "cluster_manager", + "data", + "ingest", + "remote_cluster_client" + ], + "attributes" : { + "testattr" : "test", + "shard_indexing_pressure_enabled" : "true" + }, + "search_pipeline" : { + "total_request" : { + "count" : 5, + "time_in_millis" : 158, + "current" : 0, + "failed" : 0 + }, + "total_response" : { + "count" : 2, + "time_in_millis" : 1, + "current" : 0, + "failed" : 0 + }, + "pipelines" : { + "public_info" : { + "request" : { + "count" : 3, + "time_in_millis" : 71, + "current" : 0, + "failed" : 0 + }, + "response" : { + "count" : 0, + "time_in_millis" : 0, + "current" : 0, + "failed" : 0 + }, + "request_processors" : [ + { + "filter_query:abc" : { + "type" : "filter_query", + "stats" : { + "count" : 1, + "time_in_millis" : 0, + "current" : 0, + "failed" : 0 + } + } + }, + { + "filter_query" : { + "type" : "filter_query", + "stats" : { + "count" : 4, + "time_in_millis" : 2, + "current" : 0, + "failed" : 0 + } + } + } + ], + "response_processors" : [ ] + }, + "guest_pipeline" : { + "request" : { + "count" : 2, + "time_in_millis" : 87, + "current" : 0, + "failed" : 0 + }, + "response" : { + "count" : 2, + "time_in_millis" : 1, + "current" : 0, + "failed" : 0 + }, + "request_processors" : [ + { + "script" : { + "type" : "script", + "stats" : { + "count" : 2, + "time_in_millis" : 86, + "current" : 0, + "failed" : 0 + } + } + }, + { + "filter_query:abc" : { + "type" : "filter_query", + "stats" : { + "count" : 1, + "time_in_millis" : 0, + "current" : 0, + "failed" : 0 + } + } + }, + { + "filter_query" : { + "type" : "filter_query", + "stats" : { + "count" : 3, + "time_in_millis" : 0, + "current" : 0, + "failed" : 0 + } + } + } + ], + "response_processors" : [ + { + "rename_field" : { + "type" : "rename_field", + "stats" : { + "count" : 2, + "time_in_millis" : 1, + "current" : 0, + "failed" : 0 + } + } + } + ] + } + } + } + } + } +} +``` + +有关响应中各字段的说明,请参阅 [Nodes Stats 的搜索管道部分](/api-reference/nodes-apis/nodes-stats#search_pipeline)。 diff --git a/i18n/zh/search-plugins/search-pipelines/search-processors.md b/i18n/zh/search-plugins/search-pipelines/search-processors.md new file mode 100644 index 00000000..89f76b08 --- /dev/null +++ b/i18n/zh/search-plugins/search-pipelines/search-processors.md @@ -0,0 +1,116 @@ +--- +title: 搜索处理器 +--- + +# 搜索处理器 + +搜索处理器(search processor)分为以下几种类型: + +- [搜索请求处理器](#search-request-processors) +- [搜索响应处理器](#search-response-processors) +- [搜索阶段结果处理器](#search-phase-results-processors) + +## 搜索请求处理器 + +搜索请求处理器(search request processor)会拦截搜索请求(请求中传递的查询和元数据),使用或针对该搜索请求执行操作,然后将搜索请求提交给索引。 + +下表列出了所有受支持的搜索请求处理器。 + +处理器 | 描述 | 最早可用版本 +:--- | :--- | :--- +[`filter_query`](/search-plugins/search-pipelines/filter-query-processor) | 添加一个用于过滤请求的过滤查询。 | 2.8 +[`neural_query_enricher`](/search-plugins/search-pipelines/neural-query-enricher) | 在索引级别或字段级别为神经搜索设置默认模型。 | 2.11 +[`script`](/search-plugins/search-pipelines/script-processor) | 添加一个对新索引的文档运行的脚本。 | 2.8 +[`oversample`](/search-plugins/search-pipelines/oversample-processor) | 增大搜索请求的 `size` 参数,并将原始值存储在管道状态中。 | 2.12 + +## 搜索响应处理器 + +搜索响应处理器(search response processor)会拦截搜索响应和搜索请求(请求中传递的查询、结果和元数据),使用或针对该搜索响应执行操作,然后返回搜索响应。 + +下表列出了所有受支持的搜索响应处理器。 + +处理器 | 描述 | 最早可用版本 +:--- | :--- | :--- +[`personalize_search_ranking`](/search-plugins/search-pipelines/personalize-search-ranking) | 使用 [Amazon Personalize](https://aws.amazon.com/personalize/) 对搜索结果进行重排序(需要设置 Amazon Personalize 服务)。 | 2.9 +[`retrieval_augmented_generation`](/search-plugins/search-pipelines/rag-processor) | 用于[对话式搜索](/search-plugins/conversational-search)中的检索增强生成(RAG)。 | 2.10(在 2.12 中正式发布) +[`rename_field`](/search-plugins/search-pipelines/rename-field-processor)| 重命名现有字段。 | 2.8 +[`rerank`](/search-plugins/search-pipelines/rerank-processor)| 使用交叉编码器模型对搜索结果进行重排序。 | 2.12 +[`collapse`](/search-plugins/search-pipelines/collapse-processor)| 根据字段值对搜索命中进行去重,与搜索请求中的 `collapse` 类似。 | 2.12 +[`truncate_hits`](/search-plugins/search-pipelines/truncate-hits-processor)| 在达到指定的目标数量后丢弃其余搜索命中。可以抵消 `oversample` 请求处理器的效果。 | 2.12 + +## 搜索阶段结果处理器 + +搜索阶段结果处理器(search phase results processor)在协调节点层面、于各搜索阶段之间运行。它会拦截某一搜索阶段检索到的结果,对其进行转换后再传递给下一个搜索阶段。 + +下表列出了所有受支持的搜索阶段结果处理器。 + +处理器 | 描述 | 最早可用版本 +:--- | :--- | :--- +[`normalization-processor`](/search-plugins/search-pipelines/normalization-processor) | 拦截查询阶段的结果,对文档评分进行归一化和组合,然后再将文档传递给获取阶段。 | 2.10 + +## 查看可用的处理器类型 + +可以使用 Nodes Search Pipelines API 查看可用的处理器类型: + +```json +GET /_nodes/search_pipelines +``` + +响应包含 `search_pipelines` 对象,其中列出了可用的请求处理器和响应处理器: + +
+ + 响应 + + +```json +{ + "_nodes" : { + "total" : 1, + "successful" : 1, + "failed" : 0 + }, + "cluster_name" : "runTask", + "nodes" : { + "36FHvCwHT6Srbm2ZniEPhA" : { + "name" : "runTask-0", + "transport_address" : "127.0.0.1:9300", + "host" : "127.0.0.1", + "ip" : "127.0.0.1", + "version" : "3.0.0", + "build_type" : "tar", + "build_hash" : "unknown", + "roles" : [ + "cluster_manager", + "data", + "ingest", + "remote_cluster_client" + ], + "attributes" : { + "testattr" : "test", + "shard_indexing_pressure_enabled" : "true" + }, + "search_pipelines" : { + "request_processors" : [ + { + "type" : "filter_query" + }, + { + "type" : "script" + } + ], + "response_processors" : [ + { + "type" : "rename_field" + } + ] + } + } + } +} +``` +
+ +::: info 注意 +除了 OpenSearch 提供的处理器之外,插件也可能提供其他处理器。 +::: diff --git a/i18n/zh/search-plugins/search-pipelines/truncate-hits-processor.md b/i18n/zh/search-plugins/search-pipelines/truncate-hits-processor.md new file mode 100644 index 00000000..9889c74d --- /dev/null +++ b/i18n/zh/search-plugins/search-pipelines/truncate-hits-processor.md @@ -0,0 +1,491 @@ +--- +title: Truncate hits +--- + +# Truncate hits 处理器 + +`truncate_hits` 响应处理器在达到给定的命中数后丢弃其余返回的搜索命中。`truncate_hits` 处理器设计用于配合 [`oversample` 请求处理器](/search-plugins/search-pipelines/oversample-processor)使用,但也可以单独使用。 + +`target_size` 参数(指定在何处截断)是可选的。如果未指定,OpenSearch 会使用 `oversample` 处理器设置的 `original_size` 变量(如果存在)。 + +以下是一种常见的使用模式: + +1. 将 `oversample` 处理器添加到请求管道中,以获取更大的结果集。 +1. 在响应管道中,应用重排序处理器(可能会把原先请求的前 N 个之外的结果提升上来)或 `collapse` 处理器(去重后可能会丢弃部分结果)。 +1. 应用 `truncate` 处理器,返回(最多)原先请求数量的命中。 + +## 请求字段 + +下表列出了所有请求字段。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`target_size` | Integer | 要返回的搜索命中的最大数量(>=0)。如果未指定,处理器会尝试读取 `original_size` 变量,如果该变量不可用,处理器将失败。可选。 +`context_prefix` | String | 可用于从特定作用域读取 `original_size` 变量,以避免冲突。可选。 +`tag` | String | 处理器的标识符。可选。 +`description` | String | 处理器的描述。可选。 +`ignore_failure` | Boolean | 如果为 `true`,OpenSearch 会[忽略该处理器的任何失败](/search-plugins/search-pipelines/creating-search-pipeline#ignoring-processor-failures),并继续运行搜索管道中剩余的处理器。可选。默认值为 `false`。 + +## 示例 + +以下示例演示如何使用包含 `truncate` 处理器的搜索管道。 + +### 准备工作 + +创建一个名为 `my_index` 的索引,其中包含多个文档: + +```json +POST /_bulk +{ "create":{"_index":"my_index","_id":1}} +{ "doc": { "title" : "document 1" }} +{ "create":{"_index":"my_index","_id":2}} +{ "doc": { "title" : "document 2" }} +{ "create":{"_index":"my_index","_id":3}} +{ "doc": { "title" : "document 3" }} +{ "create":{"_index":"my_index","_id":4}} +{ "doc": { "title" : "document 4" }} +{ "create":{"_index":"my_index","_id":5}} +{ "doc": { "title" : "document 5" }} +{ "create":{"_index":"my_index","_id":6}} +{ "doc": { "title" : "document 6" }} +{ "create":{"_index":"my_index","_id":7}} +{ "doc": { "title" : "document 7" }} +{ "create":{"_index":"my_index","_id":8}} +{ "doc": { "title" : "document 8" }} +{ "create":{"_index":"my_index","_id":9}} +{ "doc": { "title" : "document 9" }} +{ "create":{"_index":"my_index","_id":10}} +{ "doc": { "title" : "document 10" }} +``` + +### 创建搜索管道 + +以下请求创建一个名为 `my_pipeline` 的搜索管道,其中包含一个 `truncate_hits` 响应处理器,该处理器会丢弃前五个之后的命中: + +```json +PUT /_search/pipeline/my_pipeline +{ + "response_processors": [ + { + "truncate_hits" : { + "tag" : "truncate_1", + "description" : "This processor will discard results after the first 5.", + "target_size" : 5 + } + } + ] +} +``` + +### 使用搜索管道 + +不使用搜索管道,在 `my_index` 中搜索文档: + +```json +POST /my_index/_search +{ + "size": 8 +} +``` + +响应包含八个命中: + +
+ + 响应 + + +```json +{ + "took" : 13, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 10, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "my_index", + "_id" : "1", + "_score" : 1.0, + "_source" : { + "doc" : { + "title" : "document 1" + } + } + }, + { + "_index" : "my_index", + "_id" : "2", + "_score" : 1.0, + "_source" : { + "doc" : { + "title" : "document 2" + } + } + }, + { + "_index" : "my_index", + "_id" : "3", + "_score" : 1.0, + "_source" : { + "doc" : { + "title" : "document 3" + } + } + }, + { + "_index" : "my_index", + "_id" : "4", + "_score" : 1.0, + "_source" : { + "doc" : { + "title" : "document 4" + } + } + }, + { + "_index" : "my_index", + "_id" : "5", + "_score" : 1.0, + "_source" : { + "doc" : { + "title" : "document 5" + } + } + }, + { + "_index" : "my_index", + "_id" : "6", + "_score" : 1.0, + "_source" : { + "doc" : { + "title" : "document 6" + } + } + }, + { + "_index" : "my_index", + "_id" : "7", + "_score" : 1.0, + "_source" : { + "doc" : { + "title" : "document 7" + } + } + }, + { + "_index" : "my_index", + "_id" : "8", + "_score" : 1.0, + "_source" : { + "doc" : { + "title" : "document 8" + } + } + } + ] + } +} +``` +
+ +要使用管道进行搜索,请在 `search_pipeline` 查询参数中指定管道名称: + +```json +POST /my_index/_search?search_pipeline=my_pipeline +{ + "size": 8 +} +``` + +尽管请求了 8 个命中且有 10 个可用,响应中只包含 5 个命中: + +
+ + 响应 + + +```json +{ + "took" : 3, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 10, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "my_index", + "_id" : "1", + "_score" : 1.0, + "_source" : { + "doc" : { + "title" : "document 1" + } + } + }, + { + "_index" : "my_index", + "_id" : "2", + "_score" : 1.0, + "_source" : { + "doc" : { + "title" : "document 2" + } + } + }, + { + "_index" : "my_index", + "_id" : "3", + "_score" : 1.0, + "_source" : { + "doc" : { + "title" : "document 3" + } + } + }, + { + "_index" : "my_index", + "_id" : "4", + "_score" : 1.0, + "_source" : { + "doc" : { + "title" : "document 4" + } + } + }, + { + "_index" : "my_index", + "_id" : "5", + "_score" : 1.0, + "_source" : { + "doc" : { + "title" : "document 5" + } + } + } + ] + } +} +``` +
+ +## 过采样、折叠与截断命中 + +下面是一个更贴近实际的示例:使用 `oversample` 请求大量候选文档,使用 `collapse` 移除在某个字段上重复的文档(以获得更多样化的结果),然后使用 `truncate` 返回原先请求的文档数量(以避免从集群返回过大的结果载荷)。 + +### 准备工作 {#setup-1} + +创建多个文档,其中包含一个将用于折叠的字段: + +```json +POST /_bulk +{ "create":{"_index":"my_index","_id":1}} +{ "title" : "document 1", "color":"blue" } +{ "create":{"_index":"my_index","_id":2}} +{ "title" : "document 2", "color":"blue" } +{ "create":{"_index":"my_index","_id":3}} +{ "title" : "document 3", "color":"red" } +{ "create":{"_index":"my_index","_id":4}} +{ "title" : "document 4", "color":"red" } +{ "create":{"_index":"my_index","_id":5}} +{ "title" : "document 5", "color":"yellow" } +{ "create":{"_index":"my_index","_id":6}} +{ "title" : "document 6", "color":"yellow" } +{ "create":{"_index":"my_index","_id":7}} +{ "title" : "document 7", "color":"orange" } +{ "create":{"_index":"my_index","_id":8}} +{ "title" : "document 8", "color":"orange" } +{ "create":{"_index":"my_index","_id":9}} +{ "title" : "document 9", "color":"green" } +{ "create":{"_index":"my_index","_id":10}} +{ "title" : "document 10", "color":"green" } +``` + +创建一个只按 `color` 字段折叠的管道: + +```json +PUT /_search/pipeline/collapse_pipeline +{ + "response_processors": [ + { + "collapse" : { + "field": "color" + } + } + ] +} +``` + +再创建一个依次进行过采样、折叠和截断结果的管道: + +```json +PUT /_search/pipeline/oversampling_collapse_pipeline +{ + "request_processors": [ + { + "oversample": { + "sample_factor": 3 + } + } + ], + "response_processors": [ + { + "collapse" : { + "field": "color" + } + }, + { + "truncate_hits": { + "description": "Truncates back to the original size before oversample increased it." + } + } + ] +} +``` + +### 不过采样直接折叠 + +在本例中,请求在按 `color` 字段折叠之前的前三个文档。由于前两个文档的 `color` 相同,第二个文档会被丢弃,因此请求返回第一个和第三个文档: + +```json +POST /my_index/_search?search_pipeline=collapse_pipeline +{ + "size": 3 +} +``` + +
+ + 响应 + + +```json +{ + "took" : 2, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 10, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "my_index", + "_id" : "1", + "_score" : 1.0, + "_source" : { + "title" : "document 1", + "color" : "blue" + } + }, + { + "_index" : "my_index", + "_id" : "3", + "_score" : 1.0, + "_source" : { + "title" : "document 3", + "color" : "red" + } + } + ] + }, + "profile" : { + "shards" : [ ] + } +} +``` +
+ +### 过采样、折叠与截断 + +现在使用 `oversampling_collapse_pipeline`,它请求前 9 个文档(将 size 乘以 3),按 `color` 去重,然后返回前 3 个命中: + +```json +POST /my_index/_search?search_pipeline=oversampling_collapse_pipeline +{ + "size": 3 +} +``` + +
+ + 响应 + + +```json +{ + "took" : 2, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 10, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "my_index", + "_id" : "1", + "_score" : 1.0, + "_source" : { + "title" : "document 1", + "color" : "blue" + } + }, + { + "_index" : "my_index", + "_id" : "3", + "_score" : 1.0, + "_source" : { + "title" : "document 3", + "color" : "red" + } + }, + { + "_index" : "my_index", + "_id" : "5", + "_score" : 1.0, + "_source" : { + "title" : "document 5", + "color" : "yellow" + } + } + ] + }, + "profile" : { + "shards" : [ ] + } +} +``` +
diff --git a/i18n/zh/search-plugins/search-pipelines/using-search-pipeline.md b/i18n/zh/search-plugins/search-pipelines/using-search-pipeline.md new file mode 100644 index 00000000..fc36220e --- /dev/null +++ b/i18n/zh/search-plugins/search-pipelines/using-search-pipeline.md @@ -0,0 +1,147 @@ +--- +title: 使用搜索管道 +--- + +# 使用搜索管道 + +可以通过以下方式使用搜索管道(Search Pipeline): + +- 为请求[指定现有管道](#specifying-an-existing-search-pipeline-for-a-request)。 +- 为请求[使用临时管道](#using-a-temporary-search-pipeline-for-a-request)。 +- 为索引中的所有请求设置[默认管道](#default-search-pipeline)。 + +## 为请求指定现有搜索管道 + +[创建搜索管道](/search-plugins/search-pipelines/creating-search-pipeline)之后,可以在 `search_pipeline` 查询参数中指定管道名称,从而在查询中使用该管道: + +```json +GET /my_index/_search?search_pipeline=my_pipeline +``` + +有关使用包含 `filter_query` 处理器的搜索管道的完整示例,请参阅 [`filter_query` 处理器示例](/search-plugins/search-pipelines/filter-query-processor#example)。 + +## 为请求使用临时搜索管道 + +除了创建搜索管道,也可以定义一个仅用于当前查询的临时搜索管道: + +```json +POST /my-index/_search +{ + "query" : { + "match" : { + "text_field" : "some search text" + } + }, + "search_pipeline" : { + "request_processors": [ + { + "filter_query" : { + "tag" : "tag1", + "description" : "This processor is going to restrict to publicly visible documents", + "query" : { + "term": { + "visibility": "public" + } + } + } + } + ], + "response_processors": [ + { + "rename_field": { + "field": "message", + "target_field": "notification" + } + } + ] + } +} +``` + +使用这种语法时,管道不会被持久保存,只用于指定了它的那次查询。 + +## 默认搜索管道 + +为了方便起见,可以为索引设置默认搜索管道。索引有了默认管道之后,就无需在每个搜索请求中指定 `search_pipeline` 查询参数。 + +### 为索引设置默认搜索管道 + +要为索引设置默认搜索管道,请在索引设置中指定 `index.search.default_pipeline`: + +```json +PUT /my_index/_settings +{ + "index.search.default_pipeline" : "my_pipeline" +} +``` + +为 `my_index` 设置默认管道后,可以再次尝试同样的搜索所有文档的请求: + +```json +GET /my_index/_search +``` + +响应中只包含公开文档,说明管道已被默认应用: + +
+ + 响应 + + +```json +{ + "took" : 19, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 0.0, + "hits" : [ + { + "_index" : "my_index", + "_id" : "1", + "_score" : 0.0, + "_source" : { + "message" : "This is a public message", + "visibility" : "public" + } + } + ] + } +} +``` +
+ +### 为请求禁用默认管道 + +如果希望在不应用默认管道的情况下运行搜索请求,可以将 `search_pipeline` 查询参数设置为 `_none`: + +```json +GET /my_index/_search?search_pipeline=_none +``` + +### 移除默认管道 + +要从索引中移除默认管道,请将其设置为 `null` 或 `_none`: + +```json +PUT /my_index/_settings +{ + "index.search.default_pipeline" : null +} +``` + +```json +PUT /my_index/_settings +{ + "index.search.default_pipeline" : "_none" +} +``` diff --git a/i18n/zh/search-plugins/search-relevance/compare-search-results.md b/i18n/zh/search-plugins/search-relevance/compare-search-results.md new file mode 100644 index 00000000..fa299aca --- /dev/null +++ b/i18n/zh/search-plugins/search-relevance/compare-search-results.md @@ -0,0 +1,163 @@ +--- +title: 比较搜索结果 +--- + +# 比较搜索结果 + +借助 OpenSearch Dashboards 中的 Compare Search Results(比较搜索结果)工具,你可以并排比较两个查询的结果,判断其中一个查询是否比另一个产生更好的结果。使用该工具,你可以通过试验不同的查询来评估搜索质量。 + +例如,你可以观察在应用以下某种查询变更后,结果会发生怎样的变化: + +- 为字段设置不同的权重 +- 采用不同的词干提取(stemming)或词形还原(lemmatization)策略 +- 使用 shingle + +## 前提条件 + +开始之前,必须先在 OpenSearch 中索引数据。要了解如何创建新索引,请参阅[索引数据](/im-plugin/)。 + +此外,也可以按以下步骤在 OpenSearch Dashboards 中添加示例数据: + +1. 在顶部菜单栏中,转到 **OpenSearch Dashboards > Overview**。 +1. 选择 **View app directory**。 +1. 选择 **Add sample data**。 +1. 选择一个内置数据集,然后选择 **Add data**。 + +## 在 OpenSearch Dashboards 中使用 Compare Search Results + +要在 OpenSearch Dashboards 中比较搜索结果,请执行以下步骤。 + +**第 1 步:** 在顶部菜单栏中,转到 **OpenSearch Plugins > Search Relevance**。 + +**第 2 步:** 在搜索栏中输入搜索文本。 + +**第 3 步:** 为 **Query 1** 选择一个索引,并用 [OpenSearch Query DSL](/query-dsl/) 输入查询(仅请求体)。`GET` HTTP 方法和 `_search` 端点是隐含的。使用 `%SearchText%` 变量引用搜索栏中的文本。 + +以下是一个示例查询: + +```json +{ + "query": { + "multi_match": { + "query": "%SearchText%", + "fields": [ "description", "item_name" ] + } + } +} +``` + +**第 4 步:** 为 **Query 2** 选择一个索引并输入查询(仅请求体)。 + +以下示例查询在搜索结果中提升了 `title` 字段的权重: + +```json +{ + "query": { + "multi_match": { + "query": "%SearchText%", + "fields": [ "description", "item_name^3" ] + } + } +} +``` + +**第 5 步:** 选择 **Search**,然后比较 **Result 1** 和 **Result 2**。 + +以下示例界面展示了在 `description` 和 `item_name` 字段中搜索单词“cup”时,对 `item_name` 进行权重提升与不提升的对比。 + +Compare search results + +如果 Result 1 中的某个结果也出现在 Result 2 中,结果编号下方的 `Up` 和 `Down` 指示符表示该结果相对于 Result 2 中同一结果上移或下移了多少位。在本例中,ID 为 2 的文档在 Result 2 中相对于 Result 1 是 `Up 1`(上移 1 位),在 Result 1 中相对于 Result 2 是 `Down 1`(下移 1 位)。 + +## 更改结果数量 + +默认情况下,OpenSearch 返回前 10 个结果。要将返回的结果数量更改为其他值,请在查询中指定 `size` 参数: + +```json +{ + "size": 15, + "query": { + "multi_match": { + "query": "%SearchText%", + "fields": [ "title^3", "text" ] + } + } +} +``` + +::: info 注意 +将 `size` 设置为较大的值(例如超过 250 个文档)可能会降低性能。 +::: + +::: info 注意 +无法保存某次比较以供日后使用,因此 Compare Search Results 不适合用于系统化测试。 +::: + +## 将 OpenSearch 搜索结果与重排序后的结果进行比较 + +Compare Search Results 的一个用例是将 OpenSearch 的原始结果与经过重排序应用处理后的同一结果进行比较。OpenSearch 目前集成了以下两种重排序器: + +- [Amazon Kendra Intelligent Ranking for OpenSearch](#reranking-results-with-amazon-kendra-intelligent-ranking-for-opensearch) +- [Amazon Personalize Search Ranking](#personalizing-search-results-with-amazon-personalize-search-ranking) + +### 使用 Amazon Kendra Intelligent Ranking for OpenSearch 对结果进行重排序 + +重排序器的一个例子是由 Amazon Kendra 团队贡献的 **Amazon Kendra Intelligent Ranking for OpenSearch**。该插件获取 OpenSearch 的搜索结果,并应用 Amazon Kendra 的语义相关性排名,该排名是利用向量嵌入和其他语义搜索技术计算得出的。对许多应用而言,这能提供更好的结果排名。 + +要试用 Amazon Kendra Intelligent Ranking,必须先设置 Amazon Kendra 服务。要开始使用,请参阅 [Amazon Kendra](https://aws.amazon.com/kendra/)。有关详细信息(包括插件设置说明),请参阅 [Amazon Kendra Intelligent Ranking for self-managed OpenSearch](https://docs.aws.amazon.com/kendra/latest/dg/opensearch-rerank.html)。 + +### 在 OpenSearch Dashboards 中将搜索结果与重排序后的结果进行比较 + +要在 OpenSearch Dashboards 中将搜索结果与重排序后的结果进行比较,请在 **Query 1** 中输入查询,并在 **Query 2** 中输入使用重排序器的同一查询。然后比较 OpenSearch 结果与重排序后的结果。 + +以下示例演示了在 `abo` 索引中搜索文本“snacking nuts”。索引中的文档在 `bullet_point` 数组中包含零食描述。 + +OpenSearch Intelligent Ranking query + +1. 在搜索栏中输入 `snacking nuts`。 +1. 在 **Query 1** 中输入以下查询,该查询在 `bullet_point` 字段中搜索文本“snacking nuts”: + + ```json + { + "query": { + "match": { + "bullet_point": "%SearchText%" + } + }, + "size": 25 + } + ``` +1. 在 **Query 2** 中输入使用重排序器的同一查询。本例使用 Amazon Kendra Intelligent Ranking: + + ```json + { + "query" : { + "match" : { + "bullet_point": "%SearchText%" + } + }, + "size": 25, + "ext": { + "search_configuration":{ + "result_transformer" : { + "kendra_intelligent_ranking": { + "order": 1, + "properties": { + "title_field": "item_name", + "body_field": "bullet_point" + } + } + } + } + } + } + ``` + + 在上述查询中,`body_field` 指索引中文档的正文字段,Amazon Kendra Intelligent Ranking 使用该字段对结果进行排名。`body_field` 是必需的,而 `title_field` 是可选的。 +1. 选择 **Search**,然后比较 **Result 1** 和 **Result 2** 中的结果。 + +### 使用 Amazon Personalize Search Ranking 对搜索结果进行个性化 + +重排序器的另一个例子是由 Amazon Personalize 团队贡献的 **Amazon Personalize Search Ranking**。Amazon Personalize 使用机器学习(ML)技术为用户生成定制化的推荐。该插件获取 OpenSearch 的搜索结果,并应用[搜索管道](/search-plugins/search-pipelines/),按照 Amazon Personalize 的排名对结果进行重排序。Amazon Personalize 的排名基于用户过去的行为,以及有关搜索条目和用户的元数据。这一工作流通过对搜索结果进行个性化,改善了用户的搜索体验。 + +要试用 Amazon Personalize Search Ranking,必须先设置 Amazon Personalize。要开始使用,请参阅 [Amazon Personalize](https://docs.aws.amazon.com/personalize/latest/dg/setup.html)。有关详细信息(包括插件设置说明),请参阅[对来自 OpenSearch 的搜索结果进行个性化](https://docs.aws.amazon.com/personalize/latest/dg/personalize-opensearch.html)。 diff --git a/i18n/zh/search-plugins/search-relevance/index.md b/i18n/zh/search-plugins/search-relevance/index.md new file mode 100644 index 00000000..ab08b57a --- /dev/null +++ b/i18n/zh/search-plugins/search-relevance/index.md @@ -0,0 +1,15 @@ +--- +title: 搜索相关性 +--- + +# 搜索相关性 + +搜索相关性(search relevance)用于评估查询返回的搜索结果的准确程度。相关性越高,搜索引擎就越好。 + +OpenSearch 提供以下搜索相关性功能: + +- 在 OpenSearch Dashboards 中并排[比较两个查询的搜索结果](/search-plugins/search-relevance/compare-search-results)。 + +- 使用交叉编码器(cross-encoder)重排序器[对搜索结果进行重排序](/search-plugins/search-relevance/reranking-search-results)。 + +- 使用 [Querqy](/search-plugins/querqy/) 改写查询。 diff --git a/i18n/zh/search-plugins/search-relevance/reranking-search-results.md b/i18n/zh/search-plugins/search-relevance/reranking-search-results.md new file mode 100644 index 00000000..a23b83a9 --- /dev/null +++ b/i18n/zh/search-plugins/search-relevance/reranking-search-results.md @@ -0,0 +1,110 @@ +--- +title: 对搜索结果进行重排序 +--- + +# 对搜索结果进行重排序 + + +可以使用交叉编码器(cross-encoder)重排序器对搜索结果进行重排序(reranking),以提高搜索相关性。要实现重排序,需要配置一个在搜索时运行的[搜索管道](/search-plugins/search-pipelines/)(Search Pipeline)。该搜索管道会拦截搜索结果,并对其应用 [`rerank` 处理器](/search-plugins/search-pipelines/rerank-processor)。`rerank` 处理器会评估搜索结果,并根据交叉编码器模型提供的新评分对结果进行排序。 + +::: info 注意 +**前提条件**
+配置重排序管道之前,必须先设置交叉编码器模型。有关使用 OpenSearch 提供的模型的信息,请参阅[交叉编码器模型](/ml-commons-plugin/pretrained-models#cross-encoder-models)。有关使用自定义模型的信息,请参阅[自定义本地模型](/ml-commons-plugin/custom-local-models)。 +::: + +## 运行带重排序的搜索 + +要运行带重排序的搜索,请按以下步骤操作: + +1. [配置搜索管道](#step-1-configure-a-search-pipeline)。 +1. [创建用于摄取的索引](#step-2-create-an-index-for-ingestion)。 +1. [将文档摄取到索引中](#step-3-ingest-documents-into-the-index)。 +1. [使用重排序进行搜索](#step-4-search-using-reranking)。 + +## 第 1 步:配置搜索管道 + +接下来,配置一个包含 [`rerank` 处理器](/search-plugins/search-pipelines/rerank-processor)的搜索管道。 + +以下示例请求创建一个包含 `ml_opensearch` rerank 处理器的搜索管道。在请求中,提供交叉编码器模型的模型 ID 以及用作上下文的文档字段: + +```json +PUT /_search/pipeline/my_pipeline +{ + "description": "Pipeline for reranking with a cross-encoder", + "response_processors": [ + { + "rerank": { + "ml_opensearch": { + "model_id": "gnDIbI0BfUsSoeNT_jAw" + }, + "context": { + "document_fields": [ + "passage_text" + ] + } + } + } + ] +} +``` + +有关请求字段的更多信息,请参阅[请求字段](/search-plugins/search-pipelines/rerank-processor#request-fields)。 + +## 第 2 步:创建用于摄取的索引 + +要使用管道中定义的 rerank 处理器,请创建一个 OpenSearch 索引,并将上一步创建的管道设置为默认管道: + +```json +PUT /my-index +{ + "settings": { + "index.search.default_pipeline" : "my_pipeline" + }, + "mappings": { + "properties": { + "passage_text": { + "type": "text" + } + } + } +} +``` + +## 第 3 步:将文档摄取到索引中 + +要将文档摄取到上一步创建的索引中,请发送以下批量请求: + +```json +POST /_bulk +{ "index": { "_index": "my-index" } } +{ "passage_text" : "I said welcome to them and we entered the house" } +{ "index": { "_index": "my-index" } } +{ "passage_text" : "I feel welcomed in their family" } +{ "index": { "_index": "my-index" } } +{ "passage_text" : "Welcoming gifts are great" } + +``` + +## 第 4 步:使用重排序进行搜索 + +要对索引执行重排序搜索,可以使用任意 OpenSearch 查询,并额外提供一个 `ext.rerank` 字段: + +```json +POST /my-index/_search +{ + "query": { + "match": { + "passage_text": "how to welcome in family" + } + }, + "ext": { + "rerank": { + "query_context": { + "query_text": "how to welcome in family" + } + } + } +} +``` + +此外,也可以提供包含上下文的字段的完整路径。有关更多信息,请参阅 [Rerank 处理器示例](/search-plugins/search-pipelines/rerank-processor#example)。 diff --git a/i18n/zh/search-plugins/search-relevance/stats-api.md b/i18n/zh/search-plugins/search-relevance/stats-api.md new file mode 100644 index 00000000..a8f4615a --- /dev/null +++ b/i18n/zh/search-plugins/search-relevance/stats-api.md @@ -0,0 +1,109 @@ +--- +title: Search Relevance Stats API +--- + +# Search Relevance Stats API + + +Search Relevance Stats API 提供有关 [Search Relevance 插件](https://github.com/opensearch-project/dashboards-search-relevance)操作的信息。Search Relevance 插件负责处理由 Dashboards 工具 [Compare Search Results](/search-plugins/search-relevance/) 发送的操作。 + +Search Relevance Stats API 会采集收到请求时所在的一分钟时间间隔内的统计信息。例如,如果请求在 23:59:59.004 收到,则采集 23:58:00.000--23:58:59.999 这一时间间隔的统计信息。 + +要更改采集统计信息的默认时间间隔,请在 `opensearch_dashboards.yml` 文件中将 `searchRelevanceDashboards.metrics.metricInterval` 设置更新为新的时间间隔(以毫秒为单位)。`opensearch_dashboards.yml` 文件位于 OpenSearch Dashboards 安装目录的 `config` 文件夹中。例如,以下设置将时间间隔设为一秒: + +```yml +searchRelevanceDashboards.metrics.metricInterval: 1000 +``` + +#### 示例请求 + +可以通过以下格式的 URL 地址访问 Search Relevance Stats API: + +``` +/api/relevancy/stats +``` + +::: info 注意 +如果在 OpenSearch 配置文件中指定了端口号,OpenSearch Dashboards 的端点地址中可能会包含该端口号。具体的 URL 格式取决于 OpenSearch 的部署类型及其所在的网络环境。 +::: + +可以通过以下两种方式查询该端点: + + - 在浏览器中访问端点地址(例如 `http://localhost:5601/api/relevancy/stats`) + + - 在终端中使用 `curl` 命令: + ```bash + curl -X GET http://localhost:5601/api/relevancy/stats + ``` + +#### 示例响应 + +以下是上述请求的响应: + +```json +{ + "data": { + "search_relevance": { + "fetch_index": { + "200": { + "response_time_total": 28.79286289215088, + "count": 1 + } + }, + "single_search": { + "200": { + "response_time_total": 29.817723274230957, + "count": 1 + } + }, + "comparison_search": { + "200": { + "response_time_total": 13.265346050262451, + "count": 2 + } + } + } + }, + "overall": { + "response_time_avg": 17.968983054161072, + "requests_per_second": 0.06666666666666667 + }, + "counts_by_component": { + "search_relevance": 4 + }, + "counts_by_status_code": { + "200": 4 + } +} +``` + +## 响应字段 + +下表列出了所有响应字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| [`data.search_relevance`](#the-datasearch_relevance-object) | Object | 与 Search Relevance 操作相关的统计信息。 | +| `overall` | Object | 所有操作的平均统计信息。 | +| `overall.response_time_avg` | Double | 所有操作的平均响应时间,以毫秒为单位。 | +| `overall.requests_per_second` | Double | 所有操作的平均每秒请求数。 | +| `counts_by_component` | Object | `data` 对象所有子对象的 `count` 值之和。 | +| `counts_by_component.search_relevance` | `search_relevance` 对象中所有操作的响应总数。 | +| `counts_by_status_code` | Object | 包含所有 Search Relevance 操作的响应码及其计数的列表。 | + +### `data.search_relevance` 对象 {#the-datasearchrelevance-object} + +`data.search_relevance` 对象包含下表所述的字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `comparison_search` | Object | 与比较搜索操作相关的统计信息。比较搜索操作是指在 Compare Search Results 工具中同时输入 Query 1 和 Query 2 时,比较这两个查询的请求。 | +| `single_search` | Object | 与单次搜索操作相关的统计信息。单次搜索操作是指在 Compare Search Results 工具中只输入了 Query 1 或 Query 2(而非两者都输入)时,运行单个查询的请求。 | +| `fetch_index` | Object | 与为比较搜索或单次搜索获取一个或多个索引的操作相关的统计信息。 | + +`comparison_search`、`single_search` 和 `fetch_index` 对象都包含一个 HTTP 响应码列表。下表列出了每个响应码的字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `response_time_total` | Double | 具有该 HTTP 状态码的响应的响应时间之和,以毫秒为单位。 | +| `count` | Integer | 具有该 HTTP 状态码的响应总数。 | diff --git a/i18n/zh/search-plugins/searching-data/autocomplete.md b/i18n/zh/search-plugins/searching-data/autocomplete.md new file mode 100644 index 00000000..67020dd1 --- /dev/null +++ b/i18n/zh/search-plugins/searching-data/autocomplete.md @@ -0,0 +1,1027 @@ +--- +title: 自动补全 +--- + +# 自动补全功能 + +自动补全(autocomplete)会在用户输入时向其显示建议。 + +例如,如果用户输入 "pop",OpenSearch 会提供 "popcorn" 或 "popsicles" 之类的建议。这些建议可以预判用户的意图,引导用户更快地找到可能的搜索词。 + +在 OpenSearch 中,可以设计出随每次击键更新、提供少量相关建议并且能够容忍拼写错误的自动补全功能。 + +可以使用以下方法之一实现自动补全: + +- [前缀匹配](#prefix-matching) +- [Edge n-gram 匹配](#edge-n-gram-matching) +- [边输入边搜索](#search-as-you-type) +- [补全建议器](#completion-suggester) + +前缀匹配在查询时进行,其他三种方法则在索引时进行。下文将分别介绍所有方法。 + +## 前缀匹配 + +前缀匹配(prefix matching)会查找与查询字符串中最后一个词项相匹配的文档。 + +例如,假设用户在搜索界面中输入了 "qui"。要自动补全这个短语,可以使用 `match_phrase_prefix` 查询,搜索所有以前缀 "qui" 开头的 `text_entry` 字段(field)值: + +```json +GET shakespeare/_search +{ + "query": { + "match_phrase_prefix": { + "text_entry": { + "query": "qui", + "slop": 3 + } + } + } +} +``` + +要让词序和相对位置更灵活,请指定 `slop` 值。要了解 `slop` 选项,请参阅 [Slop](/query-dsl/full-text/match-phrase#slop)。 + +前缀匹配不需要任何特殊的映射(mapping),可以直接使用现有数据。 +不过,这是一种相当消耗资源的操作。前缀 `a` 可能会匹配数十万个词项,而且对用户也没有用处。 +要限制前缀扩展的影响,请将 `max_expansions` 设为一个合理的数值: + +```json +GET shakespeare/_search +{ + "query": { + "match_phrase_prefix": { + "text_entry": { + "query": "qui", + "slop": 3, + "max_expansions": 10 + } + } + } +} +``` + +查询可以扩展到的最大词项数。查询会将搜索词“扩展”为若干个匹配词项,这些词项都在 `fuzziness` 指定的距离之内。 + +查询时自动补全易于实现,代价是性能。 +在大规模实现此功能时,我们建议采用索引时解决方案。使用索引时解决方案,索引速度可能会变慢,但这个代价只需付出一次,而不是每次查询都要付出。edge n-gram、边输入边搜索和补全建议器方法都是索引时解决方案。 + +## Edge n-gram 匹配 + +在索引过程中,edge n-gram 会把一个单词拆分成由 n 个字符组成的序列,以便更快地查找不完整的搜索词。 + +对单词 "quick" 进行 n-gram 切分时,结果取决于 n 的值。 + +n | 类型 | n-gram +:--- | :--- | :--- +1 | 一元组(Unigram) | [ `q`, `u`, `i`, `c`, `k` ] +2 | 二元组(Bigram) | [ `qu`, `ui`, `ic`, `ck` ] +3 | 三元组(Trigram) | [ `qui`, `uic`, `ick` ] +4 | 四元组(Four-gram) | [ `quic`, `uick` ] +5 | 五元组(Five-gram) | [ `quick` ] + +自动补全只需要搜索短语开头的 n-gram,因此 OpenSearch 使用一种称为 *edge n-gram* 的特殊 n-gram。 + +对单词 "quick" 进行 edge n-gram 切分,结果如下: + +- `q` +- `qu` +- `qui` +- `quic` +- `quick` + +这与用户输入的顺序相同。 + +要将字段配置为使用 edge n-gram,请创建一个带有 `edge_ngram` 过滤器的自动补全分析器(analyzer): + +```json +PUT shakespeare +{ + "mappings": { + "properties": { + "text_entry": { + "type": "text", + "analyzer": "autocomplete" + } + } + }, + "settings": { + "analysis": { + "filter": { + "edge_ngram_filter": { + "type": "edge_ngram", + "min_gram": 1, + "max_gram": 20 + } + }, + "analyzer": { + "autocomplete": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "edge_ngram_filter" + ] + } + } + } + } +} +``` + +此示例创建索引,并实例化 edge n-gram 过滤器和分析器。 + +`edge_ngram_filter` 生成的 edge n-gram 最小长度为 1(单个字母),最大长度为 20,因此它可以为最多 20 个字母的单词提供建议。 + +`autocomplete` 分析器会把字符串切分为单个词项,将词项转换为小写,然后使用 `edge_ngram_filter` 为每个词项生成 edge n-gram。 + +使用 `analyze` 操作测试此分析器: + +```json +POST shakespeare/_analyze +{ + "analyzer": "autocomplete", + "text": "quick" +} +``` + +它返回作为词元(token)的 edge n-gram: + +* `q` +* `qu` +* `qui` +* `quic` +* `quick` + +在搜索时请使用 `standard` 分析器。否则,搜索查询会被切分为 edge n-gram,你会得到与 `q`、`u` 和 `i` 匹配的所有结果。 +这是少数需要在索引时和查询时使用不同分析器的情况之一: + +```json +GET shakespeare/_search +{ + "query": { + "match": { + "text_entry": { + "query": "qui", + "analyzer": "standard" + } + } + } +} +``` + +响应中包含匹配的文档: + +```json +{ + "took": 5, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 533, + "relation": "eq" + }, + "max_score": 9.712725, + "hits": [ + { + "_index": "shakespeare", + "_id": "22006", + "_score": 9.712725, + "_source": { + "type": "line", + "line_id": 22007, + "play_name": "Antony and Cleopatra", + "speech_number": 12, + "line_number": "5.2.44", + "speaker": "CLEOPATRA", + "text_entry": "Quick, quick, good hands." + } + }, + { + "_index": "shakespeare", + "_id": "54665", + "_score": 9.712725, + "_source": { + "type": "line", + "line_id": 54666, + "play_name": "Loves Labours Lost", + "speech_number": 21, + "line_number": "5.1.52", + "speaker": "HOLOFERNES", + "text_entry": "Quis, quis, thou consonant?" + } + } + ... + ] + } +} +``` + +或者,也可以直接在映射中指定 `search_analyzer`: + +```json +"mappings": { + "properties": { + "text_entry": { + "type": "text", + "analyzer": "autocomplete", + "search_analyzer": "standard" + } + } +} +``` + +## 补全建议器 + +补全建议器(completion suggester)接受一个建议列表,并将其构建为有限状态转换器(finite-state transducer,FST)。FST 是一种经过优化的数据结构,本质上是一个图。该数据结构驻留在内存中,并针对快速前缀查找进行了优化。要了解有关 FST 的更多信息,请参阅 [Wikipedia](https://en.wikipedia.org/wiki/Finite-state_transducer)。 + +当用户输入时,补全建议器沿着匹配路径在 FST 图中逐字符移动。用户输入结束后,它会检查剩余的结尾部分,生成建议列表。 + +补全建议器可以让自动补全解决方案尽可能高效,并让你可以显式控制它给出的建议。 + +使用一种名为 [`completion`](/field-types/supported-field-types/completion) 的专用字段类型,它会在索引中存储类似 FST 的数据结构: + +```json +PUT shakespeare +{ + "mappings": { + "properties": { + "text_entry": { + "type": "completion" + } + } + } +} +``` + +要获取建议,请使用 `search` 端点和 `suggest` 参数: + +```json +GET shakespeare/_search +{ + "suggest": { + "autocomplete": { + "prefix": "To be", + "completion": { + "field": "text_entry" + } + } + } +} +``` + +短语 "to be" 与 `text_entry` 字段的 FST 进行前缀匹配: + +```json +{ + "took" : 29, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 0, + "relation" : "eq" + }, + "max_score" : null, + "hits" : [ ] + }, + "suggest" : { + "autocomplete" : [ + { + "text" : "To be", + "offset" : 0, + "length" : 5, + "options" : [ + { + "text" : "To be a comrade with the wolf and owl,--", + "_index" : "shakespeare", + "_id" : "50652", + "_score" : 1.0, + "_source" : { + "type" : "line", + "line_id" : 50653, + "play_name" : "King Lear", + "speech_number" : 68, + "line_number" : "2.4.230", + "speaker" : "KING LEAR", + "text_entry" : "To be a comrade with the wolf and owl,--" + } + }, + { + "text" : "To be a make-peace shall become my age:", + "_index" : "shakespeare", + "_id" : "78566", + "_score" : 1.0, + "_source" : { + "type" : "line", + "line_id" : 78567, + "play_name" : "Richard II", + "speech_number" : 20, + "line_number" : "1.1.160", + "speaker" : "JOHN OF GAUNT", + "text_entry" : "To be a make-peace shall become my age:" + } + }, + { + "text" : "To be a party in this injury.", + "_index" : "shakespeare", + "_id" : "75259", + "_score" : 1.0, + "_source" : { + "type" : "line", + "line_id" : 75260, + "play_name" : "Othello", + "speech_number" : 57, + "line_number" : "5.1.93", + "speaker" : "IAGO", + "text_entry" : "To be a party in this injury." + } + }, + { + "text" : "To be a preparation gainst the Polack;", + "_index" : "shakespeare", + "_id" : "33591", + "_score" : 1.0, + "_source" : { + "type" : "line", + "line_id" : 33592, + "play_name" : "Hamlet", + "speech_number" : 17, + "line_number" : "2.2.67", + "speaker" : "VOLTIMAND", + "text_entry" : "To be a preparation gainst the Polack;" + } + }, + { + "text" : "To be a public spectacle to all:", + "_index" : "shakespeare", + "_id" : "3709", + "_score" : 1.0, + "_source" : { + "type" : "line", + "line_id" : 3710, + "play_name" : "Henry VI Part 1", + "speech_number" : 6, + "line_number" : "1.4.41", + "speaker" : "TALBOT", + "text_entry" : "To be a public spectacle to all:" + } + } + ] + } + ] + } +} +``` + +要指定返回的建议数量,请使用 `size` 参数: + +```json +GET shakespeare/_search +{ + "suggest": { + "autocomplete": { + "prefix": "To n", + "completion": { + "field": "text_entry", + "size": 3 + } + } + } +} +``` + +最多返回三个文档: + +```json +{ + "took" : 4109, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 0, + "relation" : "eq" + }, + "max_score" : null, + "hits" : [ ] + }, + "suggest" : { + "autocomplete" : [ + { + "text" : "To n", + "offset" : 0, + "length" : 4, + "options" : [ + { + "text" : "To NESTOR", + "_index" : "shakespeare", + "_id" : "99707", + "_score" : 1.0, + "_source" : { + "type" : "line", + "line_id" : 99708, + "play_name" : "Troilus and Cressida", + "speech_number" : 3, + "line_number" : "", + "speaker" : "ULYSSES", + "text_entry" : "To NESTOR" + } + }, + { + "text" : "To name the bigger light, and how the less,", + "_index" : "shakespeare", + "_id" : "91884", + "_score" : 1.0, + "_source" : { + "type" : "line", + "line_id" : 91885, + "play_name" : "The Tempest", + "speech_number" : 91, + "line_number" : "1.2.394", + "speaker" : "CALIBAN", + "text_entry" : "To name the bigger light, and how the less," + } + }, + { + "text" : "To nature none more bound; his training such,", + "_index" : "shakespeare", + "_id" : "40510", + "_score" : 1.0, + "_source" : { + "type" : "line", + "line_id" : 40511, + "play_name" : "Henry VIII", + "speech_number" : 18, + "line_number" : "1.2.126", + "speaker" : "KING HENRY VIII", + "text_entry" : "To nature none more bound; his training such," + } + } + ] + } + ] + } +} +``` + +`suggest` 参数只使用前缀匹配来查找建议。 +例如,文档 "To be, or not to be" 不在结果中。如果希望将特定文档作为建议返回,可以手动添加精选的建议,并为它们添加权重以确定优先级。 + +索引一个带有输入建议的文档,并为其分配权重: + +```json +PUT shakespeare/_doc/1?refresh=true +{ + "text_entry": { + "input": [ + "To n", "To be, or not to be: that is the question:" + ], + "weight": 10 + } +} +``` + +执行同样的搜索: + +```json +GET shakespeare/_search +{ + "suggest": { + "autocomplete": { + "prefix": "To n", + "completion": { + "field": "text_entry", + "size": 3 + } + } + } +} +``` + +你会看到刚才索引的文档排在第一位: + +```json +{ + "took" : 1, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 0, + "relation" : "eq" + }, + "max_score" : null, + "hits" : [ ] + }, + "suggest" : { + "autocomplete" : [ + { + "text" : "To n", + "offset" : 0, + "length" : 4, + "options" : [ + { + "text" : "To n", + "_index" : "shakespeare", + "_id" : "1", + "_score" : 10.0, + "_source" : { + "text_entry" : { + "input" : [ + "To n", + "To be, or not to be: that is the question:" + ], + "weight" : 10 + } + } + }, + { + "text" : "To NESTOR", + "_index" : "shakespeare", + "_id" : "99707", + "_score" : 1.0, + "_source" : { + "type" : "line", + "line_id" : 99708, + "play_name" : "Troilus and Cressida", + "speech_number" : 3, + "line_number" : "", + "speaker" : "ULYSSES", + "text_entry" : "To NESTOR" + } + }, + { + "text" : "To name the bigger light, and how the less,", + "_index" : "shakespeare", + "_id" : "91884", + "_score" : 1.0, + "_source" : { + "type" : "line", + "line_id" : 91885, + "play_name" : "The Tempest", + "speech_number" : 91, + "line_number" : "1.2.394", + "speaker" : "CALIBAN", + "text_entry" : "To name the bigger light, and how the less," + } + } + ] + } + ] + } +} +``` + +也可以通过指定 `fuzzy` 参数,允许查询中存在拼写错误: + +```json +GET shakespeare/_search +{ + "suggest": { + "autocomplete": { + "prefix": "rosenkrantz", + "completion": { + "field": "text_entry", + "size": 3, + "fuzzy" : { + "fuzziness" : "AUTO" + } + } + } + } +} +``` + +结果与正确的拼写相匹配: + +```json +{ + "took" : 1, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 0, + "relation" : "eq" + }, + "max_score" : null, + "hits" : [ ] + }, + "suggest" : { + "autocomplete" : [ + { + "text" : "rosenkrantz", + "offset" : 0, + "length" : 11, + "options" : [ + { + "text" : "ROSENCRANTZ:", + "_index" : "shakespeare", + "_id" : "35196", + "_score" : 5.0, + "_source" : { + "type" : "line", + "line_id" : 35197, + "play_name" : "Hamlet", + "speech_number" : 2, + "line_number" : "4.2.1", + "speaker" : "HAMLET", + "text_entry" : "ROSENCRANTZ:" + } + } + ] + } + ] + } +} +``` + +可以使用正则表达式为补全建议器查询定义前缀: + +```json +GET shakespeare/_search +{ + "suggest": { + "autocomplete": { + "prefix": "rosen*", + "completion": { + "field": "text_entry", + "size": 3 + } + } + } +} +``` + +有关更多信息,请参阅 [`completion` 字段类型文档](/field-types/supported-field-types/completion)。 + +## 边输入边搜索 + +OpenSearch 提供了一种专用的 [`search_as_you_type`](/field-types/supported-field-types/search-as-you-type) 字段类型,它针对边输入边搜索(search as you type)功能进行了优化,可以同时使用前缀补全和中缀补全来匹配词项。使用 `search_as_you_type` 字段时,不需要事先设置自定义分析器或索引建议。 + +首先,将字段映射为 `search_as_you_type`: + +```json +PUT shakespeare +{ + "mappings": { + "properties": { + "text_entry": { + "type": "search_as_you_type" + } + } + } +} +``` + +索引文档后,OpenSearch 会自动创建并存储该文档的 n-gram 和 edge n-gram。例如,以字符串 `that is the question` 为例。首先,它会使用标准分析器被切分为词项,这些词项存储在 `text_entry` 字段中: + +```json +[ + "that", + "is", + "the", + "question" +] +``` + +除了存储这些词项之外,该字段的以下 2-gram 会存储在 `text_entry._2gram` 字段中: + +```json +[ + "that is", + "is the", + "the question" +] +``` + +该字段的以下 3-gram 会存储在 `text_entry._3gram` 字段中: + +```json +[ + "that is the", + "is the question" +] +``` + +最后,应用 edge n-gram 词元过滤器之后,得到的词项会存储在 `text_entry._index_prefix` 字段中: + +```json +[ + "t", + "th", + "tha", + "that", + ... +] +``` + +然后,可以使用 `multi-match` 查询的 `bool_prefix` 类型,以任意顺序匹配词项: + +```json +GET shakespeare/_search +{ + "query": { + "multi_match": { + "query": "uncle what", + "type": "bool_prefix", + "fields": [ + "text_entry", + "text_entry._2gram", + "text_entry._3gram" + ] + } + }, + "size": 3 +} +``` + +单词出现顺序与查询中相同的文档,在结果中的排名更高: + +```json +{ + "took" : 1, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 4759, + "relation" : "eq" + }, + "max_score" : 10.437667, + "hits" : [ + { + "_index" : "shakespeare", + "_id" : "2817", + "_score" : 10.437667, + "_source" : { + "type" : "line", + "line_id" : 2818, + "play_name" : "Henry IV", + "speech_number" : 5, + "line_number" : "5.2.31", + "speaker" : "HOTSPUR", + "text_entry" : "Uncle, what news?" + } + }, + { + "_index" : "shakespeare", + "_id" : "37085", + "_score" : 9.437667, + "_source" : { + "type" : "line", + "line_id" : 37086, + "play_name" : "Henry V", + "speech_number" : 26, + "line_number" : "1.2.262", + "speaker" : "KING HENRY V", + "text_entry" : "What treasure, uncle?" + } + }, + { + "_index" : "shakespeare", + "_id" : "79274", + "_score" : 9.358302, + "_source" : { + "type" : "line", + "line_id" : 79275, + "play_name" : "Richard II", + "speech_number" : 29, + "line_number" : "2.1.187", + "speaker" : "KING RICHARD II", + "text_entry" : "Why, uncle, whats the matter?" + } + } + ] + } +} +``` + +要按顺序匹配词项,可以使用 `match_phrase_prefix` 查询: + +```json +GET shakespeare/_search +{ + "query": { + "match_phrase_prefix": { + "text_entry": "uncle wha" + } + }, + "size": 3 +} +``` + +响应中包含与前缀匹配的文档: + +```json +{ + "took" : 1, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 6, + "relation" : "eq" + }, + "max_score" : 16.37664, + "hits" : [ + { + "_index" : "shakespeare", + "_id" : "2817", + "_score" : 16.37664, + "_source" : { + "type" : "line", + "line_id" : 2818, + "play_name" : "Henry IV", + "speech_number" : 5, + "line_number" : "5.2.31", + "speaker" : "HOTSPUR", + "text_entry" : "Uncle, what news?" + } + }, + { + "_index" : "shakespeare", + "_id" : "6789", + "_score" : 16.37664, + "_source" : { + "type" : "line", + "line_id" : 6790, + "play_name" : "Henry VI Part 2", + "speech_number" : 60, + "line_number" : "1.3.202", + "speaker" : "KING HENRY VI", + "text_entry" : "Uncle, what shall we say to this in law?" + } + }, + { + "_index" : "shakespeare", + "_id" : "7877", + "_score" : 16.37664, + "_source" : { + "type" : "line", + "line_id" : 7878, + "play_name" : "Henry VI Part 2", + "speech_number" : 13, + "line_number" : "3.2.28", + "speaker" : "KING HENRY VI", + "text_entry" : "Where is our uncle? whats the matter, Suffolk?" + } + } + ] + } +} +``` + +最后,要精确匹配最后一个词项而不是将其作为前缀匹配,可以使用 `match_phrase` 查询: + +```json +GET shakespeare/_search +{ + "query": { + "match_phrase": { + "text_entry": "uncle what" + } + }, + "size": 5 +} +``` + +响应中包含精确匹配的结果: + +```json +{ + "took" : 1, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 3, + "relation" : "eq" + }, + "max_score" : 14.437452, + "hits" : [ + { + "_index" : "shakespeare", + "_id" : "2817", + "_score" : 14.437452, + "_source" : { + "type" : "line", + "line_id" : 2818, + "play_name" : "Henry IV", + "speech_number" : 5, + "line_number" : "5.2.31", + "speaker" : "HOTSPUR", + "text_entry" : "Uncle, what news?" + } + }, + { + "_index" : "shakespeare", + "_id" : "6789", + "_score" : 9.461917, + "_source" : { + "type" : "line", + "line_id" : 6790, + "play_name" : "Henry VI Part 2", + "speech_number" : 60, + "line_number" : "1.3.202", + "speaker" : "KING HENRY VI", + "text_entry" : "Uncle, what shall we say to this in law?" + } + }, + { + "_index" : "shakespeare", + "_id" : "100955", + "_score" : 8.947967, + "_source" : { + "type" : "line", + "line_id" : 100956, + "play_name" : "Troilus and Cressida", + "speech_number" : 28, + "line_number" : "3.2.98", + "speaker" : "CRESSIDA", + "text_entry" : "Well, uncle, what folly I commit, I dedicate to you." + } + } + ] + } +} +``` + +如果修改前面 `match_phrase` 查询中的文本,省略最后一个字母,那么前面响应中的所有文档都不会被返回: + +```json +GET shakespeare/_search +{ + "query": { + "match_phrase": { + "text_entry": "uncle wha" + } + } +} +``` + +结果为空: + +```json +{ + "took" : 1, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 0, + "relation" : "eq" + }, + "max_score" : null, + "hits" : [ ] + } +} +``` + +有关更多信息,请参阅 [`search_as_you_type` 字段类型文档](/field-types/supported-field-types/search-as-you-type)。 diff --git a/i18n/zh/search-plugins/searching-data/did-you-mean.md b/i18n/zh/search-plugins/searching-data/did-you-mean.md new file mode 100644 index 00000000..c866cb69 --- /dev/null +++ b/i18n/zh/search-plugins/searching-data/did-you-mean.md @@ -0,0 +1,563 @@ +--- +title: 拼写纠错(Did-you-mean) +--- + +# 拼写纠错(Did-you-mean) + +`Did-you-mean` 建议器(suggester)会针对拼写错误的搜索词显示修正建议。 + +例如,如果用户输入 "fliud",OpenSearch 会建议一个修正后的搜索词,例如 "fluid"。然后,你可以向用户推荐这个修正后的词,甚至自动更正搜索词。 + +可以使用以下方法之一实现 `did-you-mean` 建议器: + +- 使用[词项建议器(term suggester)](#term-suggester)为单个单词提供修正建议。 +- 使用[短语建议器(phrase suggester)](#phrase-suggester)为短语提供修正建议。 + +## 词项建议器 + +使用词项建议器为单个单词提供拼写修正建议。 +词项建议器使用[编辑距离(edit distance)](https://en.wikipedia.org/wiki/Edit_distance)来计算建议。 + +编辑距离是指将一个词项变成另一个词项所需执行的单字符插入、删除或替换的次数。例如,要把单词 "cat" 变成 "hats",需要把 "c" 替换为 "h",并插入一个 "s",因此这里的编辑距离为 2。 + +使用词项建议器时,不需要为索引设置任何特殊的字段映射(mapping)。默认情况下,字符串字段类型会被映射为 `text`。`text` 字段会经过分析,因此下例中的 `title` 会被切分为单个单词。索引以下文档会创建一个 `books` 索引,其中 `title` 是 `text` 字段: + +```json +PUT books/_doc/1 +{ + "title": "Design Patterns (Object-Oriented Software)" +} + +PUT books/_doc/2 +{ + "title": "Software Architecture Patterns Explained" +} +``` + +要查看字符串是如何被切分为词元(token)的,可以使用 `_analyze` 端点。要应用该字段所使用的同一个分析器(analyzer),可以在 `field` 参数中指定字段名称: + +```json +GET books/_analyze +{ + "text": "Design Patterns (Object-Oriented Software)", + "field": "title" +} +``` + +默认分析器(`standard`)会在单词边界处切分字符串、去除标点符号,并将词元转换为小写: + +```json +{ + "tokens" : [ + { + "token" : "design", + "start_offset" : 0, + "end_offset" : 6, + "type" : "", + "position" : 0 + }, + { + "token" : "patterns", + "start_offset" : 7, + "end_offset" : 15, + "type" : "", + "position" : 1 + }, + { + "token" : "object", + "start_offset" : 17, + "end_offset" : 23, + "type" : "", + "position" : 2 + }, + { + "token" : "oriented", + "start_offset" : 24, + "end_offset" : 32, + "type" : "", + "position" : 3 + }, + { + "token" : "software", + "start_offset" : 33, + "end_offset" : 41, + "type" : "", + "position" : 4 + } + ] +} +``` + +要为拼写错误的搜索词获取建议,请使用词项建议器。在 `text` 字段中指定需要建议的输入文本,并在 `field` 字段中指定从哪个字段获取建议: + +```json +GET books/_search +{ + "suggest": { + "spell-check": { + "text": "patern", + "term": { + "field": "title" + } + } + } +} +``` + +词项建议器会在 `options` 数组中返回针对输入文本的修正列表: + +```json +{ + "took" : 2, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 0, + "relation" : "eq" + }, + "max_score" : null, + "hits" : [ ] + }, + "suggest" : { + "spell-check" : [ + { + "text" : "patern", + "offset" : 0, + "length" : 6, + "options" : [ + { + "text" : "patterns", + "score" : 0.6666666, + "freq" : 2 + } + ] + } + ] + } +} +``` + +`score` 值根据编辑距离计算,评分越高,建议越好。`freq` 是频率,表示该词项在指定索引的文档中出现的次数。 + +可以在一个请求中包含多个建议。以下示例使用词项建议器生成两个不同的建议: + +```json +GET books/_search +{ + "suggest": { + "spell-check1" : { + "text" : "patern", + "term" : { + "field" : "title" + } + }, + "spell-check2" : { + "text" : "desing", + "term" : { + "field" : "title" + } + } + } +} +``` + +要针对多个字段中的同一输入文本获取建议,可以全局定义文本,以避免重复: + +```json +GET books/_search +{ + "suggest": { + "text" : "patern", + "spell-check1" : { + "term" : { + "field" : "title" + } + }, + "spell-check2" : { + "term" : { + "field" : "subject" + } + } + } +} +``` + +如果同时在全局级别和单个建议级别指定了 `text`,则建议级别的值会覆盖全局值。 + +### 词项建议器选项 + +可以为词项建议器指定以下选项。 + +选项 | 描述 +:--- | :--- +field | 获取建议的来源字段。必需。可以为每个建议单独设置,也可以全局设置。 +analyzer | 用于分析输入文本的分析器。默认为 `field` 所配置的分析器。 +size | 针对输入文本中每个词元返回的最大建议数。 +sort | 指定响应中建议的排序方式。有效值如下:
- `score`:先按相似度评分排序,再按文档频率排序,最后按词项本身排序。
- `frequency`:先按文档频率排序,再按相似度评分排序,最后按词项本身排序。 +suggest_mode | 建议模式,指定响应中应包含哪些词项的建议。有效值如下:
- `missing`:只为索引中不存在的输入文本词项返回建议。
- `popular`:只有当建议在文档中出现的频率高于原始输入文本时才返回建议。
- `always`:始终为输入文本中的每个词项返回建议。
默认值为 `missing`。 +max_edits | 建议的最大编辑距离。有效值范围为 [1, 2]。默认值为 2。 +prefix_length | 一个整数,指定开始返回建议所需匹配的前缀的最小长度。如果 `prefix_length` 长度的前缀不匹配,即使搜索词仍在编辑距离范围内,也不会返回建议。默认值为 1。较大的值可以提高拼写检查性能,因为拼写错误通常不会出现在单词开头。 +min_word_length | 建议被包含在响应中所需的最小长度。默认值为 4。 +shard_size | 从每个分片(shard)获取的最大候选建议数。考虑所有候选建议之后,返回排名前 `shard_size` 的建议。默认值等于 `size` 的值。由于词项可能位于不同分片中,分片级文档频率可能不精确。如果 `shard_size` 大于 `size`,建议的文档频率会更准确,但性能会下降。 +max_inspections | `shard_size` 的乘数因子。OpenSearch 为查找建议而检查的最大候选建议数为 `shard_size` 乘以 `max_inspection`。可能会提高准确性,但会降低性能。默认值为 5。 +min_doc_freq | 建议被返回所需出现的最小文档数或文档百分比。只返回分片级文档频率较高的建议,可能会提高准确性。有效值为表示文档频率的整数,或者表示文档百分比的 [0, 1] 范围内的浮点数。默认值为 0(禁用该功能)。 +max_term_freq | 建议被返回所能出现的最大文档数。有效值为表示文档频率的整数,或者表示文档百分比的 [0, 1] 范围内的浮点数。默认值为 0.01。排除高频词项可以提高拼写检查性能,因为高频词项通常拼写正确。使用分片级文档频率。 +string_distance | 用于判断相似度的编辑距离算法。有效值如下:
- `internal`:默认算法,基于 [Damerau-Levenshtein 算法](https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance),但针对比较索引中词项的编辑距离进行了高度优化。
- `damerau_levenshtein`:基于 [Damerau-Levenshtein 算法](https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance)的编辑距离算法。
- `levenshtein`:基于 [Levenshtein 编辑距离算法](https://en.wikipedia.org/wiki/Levenshtein_distance)的编辑距离算法。
- `jaro_winkler`:基于 [Jaro-Winkler 算法](https://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance)的编辑距离算法。
- `ngram`:基于字符 n-gram 的编辑距离算法。 + +## 短语建议器 + +要实现 `did-you-mean`,请使用短语建议器。 +短语建议器与词项建议器类似,不同之处在于它使用 n-gram 语言模型来建议完整的短语,而不是单个单词。 + +要设置短语建议器,请创建一个名为 `trigram` 的自定义分析器,它使用 `shingle` 过滤器并将词元转换为小写。该过滤器与 `edge_ngram` 过滤器类似,但作用于单词而不是字母。然后,使用所创建的自定义分析器配置作为建议来源的字段: + +```json +PUT books2 +{ + "settings": { + "index": { + "analysis": { + "analyzer": { + "trigram": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "shingle" + ] + } + }, + "filter": { + "shingle": { + "type": "shingle", + "min_shingle_size": 2, + "max_shingle_size": 3 + } + } + } + } + }, + "mappings": { + "properties": { + "title": { + "type": "text", + "fields": { + "trigram": { + "type": "text", + "analyzer": "trigram" + } + } + } + } + } +} +``` + +将文档索引到新索引中: + +```json +PUT books2/_doc/1 +{ + "title": "Design Patterns" +} + +PUT books2/_doc/2 +{ + "title": "Software Architecture Patterns Explained" +} +``` + +假设用户搜索了一个错误的短语: + +```json +GET books2/_search +{ + "suggest": { + "phrase-check": { + "text": "design paterns", + "phrase": { + "field": "title.trigram" + } + } + } +} +``` + +短语建议器返回修正后的短语: + +```json +{ + "took" : 4, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 0, + "relation" : "eq" + }, + "max_score" : null, + "hits" : [ ] + }, + "suggest" : { + "phrase-check" : [ + { + "text" : "design paterns", + "offset" : 0, + "length" : 14, + "options" : [ + { + "text" : "design patterns", + "score" : 0.31666178 + } + ] + } + ] + } +} +``` + +要高亮显示建议,请为短语建议器设置 [`highlight`](/search-plugins/searching-data/highlight) 字段: + +```json +GET books2/_search +{ + "suggest": { + "phrase-check": { + "text": "design paterns", + "phrase": { + "field": "title.trigram", + "gram_size": 3, + "highlight": { + "pre_tag": "", + "post_tag": "" + } + } + } + } +} +``` + +结果中包含高亮显示的文本: + +```json +{ + "took" : 2, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 0, + "relation" : "eq" + }, + "max_score" : null, + "hits" : [ ] + }, + "suggest" : { + "phrase-check" : [ + { + "text" : "design paterns", + "offset" : 0, + "length" : 14, + "options" : [ + { + "text" : "design patterns", + "highlighted" : "design patterns", + "score" : 0.31666178 + } + ] + } + ] + } +} +``` + +### 短语建议器选项 + +可以为短语建议器指定以下选项。 + +选项 | 描述 +:--- | :--- +field | 用于 n-gram 查找的字段。短语建议器使用该字段计算建议评分。必需。 +gram_size | 字段中 n-gram(shingle)的最大大小 `n`。如果字段不包含 n-gram(shingle),请省略此选项或将其设为 1。如果字段使用了 shingle 过滤器且未设置 `gram_size`,则 `gram_size` 会被设为 `max_shingle_size`。 +real_word_error_likelihood | 某个词项即使存在于词典中,仍然拼写错误的概率。默认值为 0.95(词典中 5% 的单词拼写错误)。 +confidence | 置信度是一个浮点因子,与输入短语的评分相乘,得到其他建议的阈值评分。只返回评分高于该阈值的建议。置信度为 1.0 时,只返回评分高于输入短语的建议。如果 `confidence` 设为 0,则返回排名前 `size` 的候选项。默认值为 1。 +max_errors | 返回建议时允许出错(拼写错误)的词项的最大数量或百分比。有效值为表示词项数量的整数,或者表示词项百分比的 (0, 1) 范围内的浮点数。默认值为 1(只返回最多包含一个拼写错误词项的建议)。将该值设得过高可能会降低性能。建议将 `max_errors` 设为 1 或 2 之类的较小值,以减少建议调用相对于查询执行所花费的时间。 +separator | 二元组(bigram)字段中词项之间的分隔符。默认为空格字符。 +size | 为每个查询词项生成的候选建议数。指定较大的值可能会返回编辑距离较大的词项。默认值为 5。 +analyzer | 用于分析建议文本的分析器。默认为 `field` 所配置的分析器。 +shard_size | 从每个分片获取的最大候选建议数。考虑所有候选建议之后,返回排名前 `shard_size` 的建议。默认值为 5。 +[collate](#collate-field)| 用于剔除在索引中没有匹配文档的建议。 +collate.query | 指定一个用于检查建议的查询,以剔除在索引中没有匹配文档的建议。 +collate.prune | 指定是否返回所有建议。如果 `prune` 设为 `false`,则只返回有匹配文档的建议。如果 `prune` 设为 `true`,则返回所有建议,并且每个建议都带有一个额外的 `collate_match` 字段:建议有匹配文档时该字段为 `true`,否则为 `false`。默认值为 `false`。 +highlight | 配置建议的高亮显示。`pre_tag` 和 `post_tag` 值都是必需的。 +highlight.pre_tag | 高亮的起始标签。 +highlight.post_tag | 高亮的结束标签。 +[smoothing](#smoothing-models) | 平滑模型,用于平衡在索引中频繁出现的 shingle 与不常出现的 shingle 的权重。 + +### Collate 字段 + +要过滤掉经拼写检查后不会返回任何结果的建议,可以使用 `collate` 字段。该字段包含一个脚本化查询,会针对每个返回的建议运行。有关构建模板化查询的信息,请参阅[搜索模板](/api-reference/search-template)。可以使用 `{{suggestion}}` 变量指定当前建议,也可以在 `params` 字段中传入自己的模板参数(建议值会被添加到所指定的变量中)。 + +建议的 collate 查询只在该建议来源的分片上运行。该查询是必需的。 + +此外,如果 `prune` 参数设为 `true`,则每个建议都会添加一个 `collate_match` 字段。如果查询没有返回结果,`collate_match` 的值为 `false`。之后可以根据 `collate_match` 字段过滤建议。`prune` 参数的默认值为 `false`。 + +例如,以下查询将 `collate` 字段配置为运行一个 `match_phrase` 查询,将 `title` 字段与当前建议进行匹配: + +```json +GET books2/_search +{ + "suggest": { + "phrase-check": { + "text": "design paterns", + "phrase": { + "field": "title.trigram", + "collate" : { + "query" : { + "source": { + "match_phrase" : { + "title": "{{suggestion}}" + } + } + }, + "prune": "true" + } + } + } + } +} +``` + +得到的建议中包含设为 `true` 的 `collate_match` 字段,这表示 `match_phrase` 查询会为该建议返回匹配的文档: + +```json +{ + "took" : 7, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 0, + "relation" : "eq" + }, + "max_score" : null, + "hits" : [ ] + }, + "suggest" : { + "phrase-check" : [ + { + "text" : "design paterns", + "offset" : 0, + "length" : 14, + "options" : [ + { + "text" : "design patterns", + "score" : 0.56759655, + "collate_match" : true + } + ] + } + ] + } +} +``` + +### 平滑模型 + +在大多数用例中,计算建议评分时,不仅要考虑 shingle 的频率,还要考虑 shingle 的大小。平滑模型(smoothing model)用于计算不同大小的 shingle 的评分,以平衡频繁出现和不常出现的 shingle 的权重。 + +支持以下平滑模型。 + +模型 | 描述 +:--- | :--- +stupid_backoff | 如果高阶 n-gram 的计数为 0,则回退到低阶 n-gram 模型,并将低阶 n-gram 模型乘以一个常数因子(`discount`)。这是默认的平滑模型。 +stupid.backoff.discount | 低阶 n-gram 模型的乘数因子。可选。默认值为 0.4。 +laplace | 使用加法平滑,向所有计数加上一个常数 `alpha` 以平衡权重。 +laplace.alpha | 加到所有计数上以平衡权重的常数,通常为 1.0 或更小。可选。默认值为 0.5。 + +默认情况下,OpenSearch 使用 Stupid Backoff 模型——一种简单的算法:从最高阶的 shingle 开始,如果找不到高阶 shingle,就使用低阶 shingle。例如,如果将短语建议器设置为使用 3-gram、2-gram 和 1-gram,Stupid Backoff 模型会先检查 3-gram。如果没有 3-gram,它会检查 2-gram,但会将评分乘以 `discount` 因子。如果没有 2-gram,它会检查 1-gram,并再次将评分乘以 `discount` 因子。Stupid Backoff 模型在大多数情况下效果良好。如果需要选择 Laplace 平滑模型,请在 `smoothing` 参数中指定: + +```json +GET books2/_search +{ + "suggest": { + "phrase-check": { + "text": "design paterns", + "phrase": { + "field": "title.trigram", + "size" : 1, + "smoothing" : { + "laplace" : { + "alpha" : 0.7 + } + } + } + } + } +} +``` + +### 候选生成器 + +候选生成器(candidate generator)根据输入文本中的词项提供可能的建议词项。目前只有一种候选生成器可用,即 `direct_generator`。直接生成器(direct generator)的工作方式与词项建议器类似:它也会针对输入文本中的每个词项调用一次。短语建议器支持多个候选生成器,每个生成器都会针对输入文本中的每个词项调用一次。它还允许指定前置过滤器(pre-filter,在输入文本词项进入拼写检查阶段之前对其进行分析的分析器)和后置过滤器(post-filter,在返回生成的建议之前对其进行分析的分析器)。 + +为短语建议器设置直接生成器: + +```json +GET books2/_search +{ + "suggest": { + "text": "design paterns", + "phrase-check": { + "phrase": { + "field": "title.trigram", + "size": 1, + "direct_generator": [ + { + "field": "title.trigram", + "suggest_mode": "always", + "min_word_length": 3 + } + ] + } + } + } +} +``` + +可以指定以下直接生成器选项。 + +选项 | 描述 +:--- | :--- +field | 获取建议的来源字段。必需。可以为每个建议单独设置,也可以全局设置。 +size | 针对输入文本中每个词元返回的最大建议数。 +suggest_mode | 建议模式,指定应包含在每个分片上生成的哪些词项的建议。建议模式应用于每个分片的建议,在合并来自不同分片的建议时不做检查。因此,如果建议模式为 `missing`,只要某个词项在一个分片中不存在而在另一个分片中存在,就会返回建议。有效值如下:
- `missing`:只为分片中不存在的输入文本词项返回建议。
- `popular`:只有当建议在分片文档中出现的频率高于原始输入文本时才返回建议。
- `always`:始终返回建议。
默认值为 `missing`。 +max_edits | 建议的最大编辑距离。有效值范围为 [1, 2]。默认值为 2。 +prefix_length | 一个整数,指定开始返回建议所需匹配的前缀的最小长度。如果 `prefix_length` 长度的前缀不匹配,即使搜索词仍在编辑距离范围内,也不会返回建议。默认值为 1。较大的值可以提高拼写检查性能,因为拼写错误通常不会出现在单词开头。 +min_word_length | 建议被包含所需的最小长度。默认值为 4。 +max_inspections | `shard_size` 的乘数因子。OpenSearch 为查找建议而检查的最大候选建议数为 `shard_size` 乘以 `max_inspection`。可能会提高准确性,但会降低性能。默认值为 5。 +min_doc_freq | 建议被返回所需出现的最小文档数或文档百分比。只返回分片级文档频率较高的建议,可能会提高准确性。有效值为表示文档频率的整数,或者表示文档百分比的 [0, 1] 范围内的浮点数。默认值为 0(禁用该功能)。 +max_term_freq | 建议被返回所能出现的最大文档数。有效值为表示文档频率的整数,或者表示文档百分比的 [0, 1] 范围内的浮点数。默认值为 0.01。排除高频词项可以提高拼写检查性能,因为高频词项通常拼写正确。使用分片级文档频率。 +pre_filter | 在生成建议之前,应用于传给生成器的每个输入文本词元的分析器。 +post_filter | 在将每个生成的建议传给短语评分器之前应用于该建议的分析器。 diff --git a/i18n/zh/search-plugins/searching-data/highlight.md b/i18n/zh/search-plugins/searching-data/highlight.md new file mode 100644 index 00000000..fb352ff4 --- /dev/null +++ b/i18n/zh/search-plugins/searching-data/highlight.md @@ -0,0 +1,964 @@ +--- +title: 高亮显示查询匹配项 +--- + +# 高亮显示查询匹配项 + +高亮(highlighting)会在结果中突出显示搜索词,从而强调查询匹配项。 + +要高亮显示搜索词,请在查询块之外添加 `highlight` 参数: + +```json +GET shakespeare/_search +{ + "query": { + "match": { + "text_entry": "life" + } + }, + "size": 3, + "highlight": { + "fields": { + "text_entry": {} + } + } +} +``` + +结果中的每个文档都包含一个 `highlight` 对象,其中显示的搜索词被 `em` 标签包裹: + +```json +{ + "took" : 3, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 805, + "relation" : "eq" + }, + "max_score" : 7.450247, + "hits" : [ + { + "_index" : "shakespeare", + "_id" : "33765", + "_score" : 7.450247, + "_source" : { + "type" : "line", + "line_id" : 33766, + "play_name" : "Hamlet", + "speech_number" : 60, + "line_number" : "2.2.233", + "speaker" : "HAMLET", + "text_entry" : "my life, except my life." + }, + "highlight" : { + "text_entry" : [ + "my life, except my life." + ] + } + }, + { + "_index" : "shakespeare", + "_id" : "51877", + "_score" : 6.873042, + "_source" : { + "type" : "line", + "line_id" : 51878, + "play_name" : "King Lear", + "speech_number" : 18, + "line_number" : "4.6.52", + "speaker" : "EDGAR", + "text_entry" : "The treasury of life, when life itself" + }, + "highlight" : { + "text_entry" : [ + "The treasury of life, when life itself" + ] + } + }, + { + "_index" : "shakespeare", + "_id" : "39245", + "_score" : 6.6167283, + "_source" : { + "type" : "line", + "line_id" : 39246, + "play_name" : "Henry V", + "speech_number" : 7, + "line_number" : "4.7.31", + "speaker" : "FLUELLEN", + "text_entry" : "mark Alexanders life well, Harry of Monmouths life" + }, + "highlight" : { + "text_entry" : [ + "mark Alexanders life well, Harry of Monmouths life" + ] + } + } + ] + } +} +``` + +高亮功能作用于字段(field)的实际内容。OpenSearch 会从存储字段(映射中设为 `true` 的字段)中获取这些内容;如果字段未存储,则从 `_source` 字段中获取。可以将 `force_source` 参数设为 `true`,强制从 `_source` 字段获取字段内容。 + +::: info 注意 +即使搜索本身使用了同义词或词干提取,`highlight` 参数也会高亮显示原始词项。 +::: + +## 获取偏移量的方法 + +要高亮显示搜索词,高亮器(highlighter)需要知道每个词项的起始和结束字符偏移量。偏移量标记了词项在原始文本中的位置。高亮器可以从以下来源获取偏移量: + +- **倒排记录(Postings)**:在索引文档时,OpenSearch 会创建倒排搜索索引——这是用于搜索文档的核心数据结构。倒排记录代表倒排搜索索引,存储每个经过分析的词项与其所在文档列表之间的映射。如果在映射[文本字段](/field-types/supported-field-types/text)时将 `index_options` 参数设为 `offsets`,OpenSearch 会将每个词项的起始和结束字符偏移量添加到倒排索引中。在高亮过程中,高亮器会直接在倒排记录上重新运行原始查询,以定位每个词项。因此,对于大字段,存储偏移量可以提高高亮效率,因为不需要重新分析文本。存储词项偏移量需要额外的磁盘空间,但占用的磁盘空间少于存储词向量。 + +- [**词向量(Term vectors)**]:如果在映射文本字段时将 [`term_vector` 参数](/field-types/supported-field-types/text#term-vector-parameter)设为 `with_positions_offsets`,高亮器会使用 `term_vector` 来高亮字段。存储词向量需要的磁盘空间最多。不过,对于大于 1 MB 的字段以及前缀或通配符之类的多词项查询,它可以加快高亮速度,因为词向量提供了对每个文档的词项字典的访问。 + +- **文本重新分析(Text reanalysis)**:如果既没有倒排记录也没有词向量,高亮器会重新分析文本以进行高亮。对于每个需要高亮的文档和字段,高亮器都会创建一个小型内存索引,并通过 Lucene 的查询执行规划器重新运行原始查询,以获取当前文档的底层匹配信息。重新分析文本适用于大多数用例。不过,对于大字段,这种方法会消耗更多的内存和时间。 + +## 高亮器类型 + +OpenSearch 支持三种高亮器实现:`plain`、`unified` 和 `fvh`(Fast Vector Highlighter)。 + +下表列出了每种高亮器获取偏移量的方法。 + +高亮器 | 获取偏移量的方法 +:--- | :--- +[`unified`](#the-unified-highlighter) | 如果 `term_vector` 设为 `with_positions_offsets`,使用词向量;
如果 `index_options` 设为 `offsets`,使用倒排记录;
否则使用文本重新分析。 +[`fvh`](#the-fvh-highlighter) | 词向量。 +[`plain`](#the-plain-highlighter) | 文本重新分析。 + +### 设置高亮器类型 + +要设置高亮器类型,请在 `type` 字段中指定: + +```json +GET shakespeare/_search +{ + "query": { + "match": { + "text_entry": "life" + } + }, + "highlight": { + "fields": { + "text_entry": { "type": "plain"} + } + } +} +``` + +### `unified` 高亮器 + +`unified` 高亮器基于 Lucene Unified Highlighter,是 OpenSearch 的默认高亮器。它将文本拆分为句子,并将这些句子视为单独的文档,使用 BM25 算法根据相似度为其评分。`unified` 高亮器既支持精确短语高亮,也支持多词项高亮,包括模糊、前缀和正则表达式。如果使用复杂查询在多个文档中高亮多个字段,建议在 `postings` 或 `term_vector` 字段上使用 `unified` 高亮器。 + +### `fvh` 高亮器 + +`fvh` 高亮器基于 Lucene Fast Vector Highlighter。要使用此高亮器,需要存储带有位置偏移量的词向量,这会增加索引大小。`fvh` 高亮器可以将多个字段中匹配的词项合并到一个结果中。它还可以根据匹配项的位置为其分配权重;因此,在高亮一个对短语匹配的权重提升高于词项匹配的查询时,可以将短语匹配排在词项匹配之前。此外,还可以配置 `fvh` 高亮器来选择所返回文本片段的边界,并且可以使用不同的标签高亮多个单词。 + +### `plain` 高亮器 + +`plain` 高亮器基于标准 Lucene 高亮器。它要求被高亮的字段单独存储或存储在 `_source` 字段中。`plain` 高亮器会模拟查询匹配逻辑,尤其是短语查询中单词的重要性和位置。它适用于大多数用例,但对于大字段可能较慢,因为它必须重新分析要高亮的文本。 + +## 高亮选项 + +下表介绍了可以在全局级别或字段级别指定的高亮选项。字段级设置会覆盖全局设置。 + +选项 | 描述 +:--- | :--- +type | 指定要使用的高亮器。有效值为 `unified`、`fvh` 和 `plain`。默认值为 `unified`。 +fields | 指定要在其中搜索待高亮文本的字段。支持通配符表达式。如果使用通配符,则只会高亮 `text` 和 `keyword` 字段。例如,可以将 `fields` 设为 `my_field*`,以包含所有以前缀 `my_field` 开头的 `text` 和 `keyword` 字段。 +force_source | 指定用于高亮的字段值应从 `_source` 字段获取,而不是从存储的字段值获取。默认值为 `false`。 +require_field_match | 指定是否只高亮包含搜索查询匹配项的字段。默认值为 `true`。要高亮所有字段,请将此选项设为 `false`。 +pre_tags | 以字符串数组的形式指定高亮文本的 HTML 起始标签。 +post_tags | 以字符串数组的形式指定高亮文本的 HTML 结束标签。 +tags_schema | 如果将此选项设为 `styled`,OpenSearch 会使用内置的标签模式。在该模式中,`pre_tags` 为 ``、``、``、``、``、``、``、``、`` 和 ``,`post_tags` 为 ``。 +boundary_chars | 合并在一个字符串中的所有边界字符。
默认值为 `".,!? \t\n"`。 +boundary_scanner | 仅对 `unified` 和 `fvh` 高亮器有效。指定是将高亮片段按句子、单词还是字符进行拆分。有效值如下:
- `sentence`:按 [BreakIterator](https://docs.oracle.com/javase/8/docs/api/java/text/BreakIterator.html) 定义的句子边界拆分高亮片段。可以在 `boundary_scanner_locale` 选项中指定 BreakIterator 的区域设置。
- `word`:按 [BreakIterator](https://docs.oracle.com/javase/8/docs/api/java/text/BreakIterator.html) 定义的单词边界拆分高亮片段。可以在 `boundary_scanner_locale` 选项中指定 BreakIterator 的区域设置。
- `chars`:在 `boundary_chars` 中列出的任意字符处拆分高亮片段。仅对 `fvh` 高亮器有效。 +boundary_scanner_locale | 为 `boundary_scanner` 提供[区域设置(locale)](https://docs.oracle.com/javase/8/docs/api/java/util/Locale.html)。有效值为语言标签(例如 `"en-US"`)。默认值为 [Locale.ROOT](https://docs.oracle.com/javase/8/docs/api/java/util/Locale.html#ROOT)。 +boundary_max_scan | 当 `fvh` 高亮器的 `boundary_scanner` 参数设为 `chars` 时,控制扫描边界字符的范围。默认值为 20。 +encoder | 指定在返回高亮片段之前是否对其进行 HTML 编码。有效值为 `default`(不编码)或 `html`(先转义 HTML 文本,再插入高亮标签)。例如,如果字段文本为 `

Hamlet

` 且 `encoder` 设为 `html`,则高亮后的文本为 `"<h3>Hamlet</h3>"`。 +fragmenter | 指定如何将文本拆分为高亮片段。仅对 `plain` 高亮器有效。有效值如下:
- `span`(默认):将文本拆分为大小相同的片段,但尽量不在高亮词项之间拆分文本。
- `simple`:将文本拆分为大小相同的片段。 +fragment_offset | 指定开始高亮的字符偏移量。仅对 `fvh` 高亮器有效。 +fragment_size | 高亮片段的大小,以字符数表示。如果 `number_of_fragments` 设为 0,则忽略 `fragment_size`。默认值为 100。 +number_of_fragments| 返回片段的最大数量。如果 `number_of_fragments` 设为 0,OpenSearch 会返回整个字段的高亮内容。默认值为 5。 +order | 高亮片段的排序顺序。将 `order` 设为 `score` 可按相关性对片段排序。每种高亮器计算相关性评分(relevance score)的算法各不相同。默认值为 `none`。 +highlight_query | 指定高亮搜索查询以外的另一个查询的匹配项。当使用较快的查询获取文档匹配项,再使用较慢的查询(例如 `rescore_query`)优化结果时,`highlight_query` 选项非常有用。建议将搜索查询包含在 `highlight_query` 中。 +matched_fields | 合并来自不同字段的匹配项来高亮一个字段。此功能最常见的用例是高亮以不同方式分析并保存在多字段(multi-field)中的文本。`matched_fields` 列表中的所有字段都必须将 `term_vector` 字段设为 `with_positions_offsets`。合并匹配项的字段是唯一被加载的字段,因此最好将其 `store` 选项设为 `yes`。仅对 `fvh` 高亮器有效。 +no_match_size | 指定没有可高亮的匹配片段时,从字段开头起返回的字符数。默认值为 0。 +phrase_limit | 文档中会被考虑的匹配短语的数量。限制 `fvh` 高亮器要分析的短语数量,以避免消耗大量内存。如果使用了 `matched_fields`,`phrase_limit` 指定每个匹配字段的短语数量。`phrase_limit` 越大,查询时间越长,内存消耗也越多。仅对 `fvh` 高亮器有效。默认值为 256。 +max_analyzer_offset | 指定高亮请求要分析的最大字符数,其余文本不会被处理。如果要高亮的文本超过此偏移量,则返回空的高亮结果。高亮请求分析的最大字符数由 `index.highlight.max_analyzed_offset` 定义,达到此限制时会返回错误。请将 `max_analyzer_offset` 设为低于 `index.highlight.max_analyzed_offset` 的值,以避免出现该错误。 + +::: info 注意 +unified 高亮器的句子扫描器会在达到 `fragment_size` 之后的第一个单词边界处拆分长度超过 `fragment_size` 的句子。要返回完整的句子而不进行拆分,请将 `fragment_size` 设为 0。 +::: + +## 更改高亮标签 + +在设计应用程序代码时,可以解析 `highlight` 对象中的结果,并对搜索词执行某种操作,例如更改其颜色、加粗、设为斜体等。 + +要更改默认的 `em` 标签,请在 `pretag` 和 `posttag` 参数中指定新标签: + +```json +GET shakespeare/_search +{ + "query": { + "match": { + "play_name": "Henry IV" + } + }, + "size": 3, + "highlight": { + "pre_tags": [ + "" + ], + "post_tags": [ + "" + ], + "fields": { + "play_name": {} + } + } +} +``` + +响应中的剧名会被新标签高亮显示: + +```json +{ + "took" : 2, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 3205, + "relation" : "eq" + }, + "max_score" : 3.548232, + "hits" : [ + { + "_index" : "shakespeare", + "_id" : "0", + "_score" : 3.548232, + "_source" : { + "type" : "act", + "line_id" : 1, + "play_name" : "Henry IV", + "speech_number" : "", + "line_number" : "", + "speaker" : "", + "text_entry" : "ACT I" + }, + "highlight" : { + "play_name" : [ + "Henry IV" + ] + } + }, + { + "_index" : "shakespeare", + "_id" : "1", + "_score" : 3.548232, + "_source" : { + "type" : "scene", + "line_id" : 2, + "play_name" : "Henry IV", + "speech_number" : "", + "line_number" : "", + "speaker" : "", + "text_entry" : "SCENE I. London. The palace." + }, + "highlight" : { + "play_name" : [ + "Henry IV" + ] + } + }, + { + "_index" : "shakespeare", + "_id" : "2", + "_score" : 3.548232, + "_source" : { + "type" : "line", + "line_id" : 3, + "play_name" : "Henry IV", + "speech_number" : "", + "line_number" : "", + "speaker" : "", + "text_entry" : "Enter KING HENRY, LORD JOHN OF LANCASTER, the EARL of WESTMORELAND, SIR WALTER BLUNT, and others" + }, + "highlight" : { + "play_name" : [ + "Henry IV" + ] + } + } + ] + } +} +``` + +## 指定高亮查询 + +默认情况下,OpenSearch 只考虑搜索查询来进行高亮。如果使用较快的查询获取文档匹配项,再使用 `rescore_query` 之类较慢的查询来优化结果,那么高亮优化后的结果会很有用。可以通过添加 `highlight_query` 来实现: + +```json +GET shakespeare/_search +{ + "query": { + "match": { + "text_entry": { + "query": "thats my name" + } + } + }, + "rescore": { + "window_size": 20, + "query": { + "rescore_query": { + "match_phrase": { + "text_entry": { + "query": "thats my name", + "slop": 1 + } + } + }, + "rescore_query_weight": 5 + } + }, + "_source": false, + "highlight": { + "order": "score", + "fields": { + "text_entry": { + "highlight_query": { + "bool": { + "must": { + "match": { + "text_entry": { + "query": "thats my name" + } + } + }, + "should": { + "match_phrase": { + "text_entry": { + "query": "that is my name", + "slop": 1, + "boost": 10.0 + } + } + }, + "minimum_should_match": 0 + } + } + } + } + } +} +``` + +## 合并来自不同字段的匹配项来高亮一个字段 + +使用 `fvh` 高亮器,可以合并来自不同字段的匹配项来高亮一个字段。此功能最常见的用例是高亮以不同方式分析并保存在多字段中的文本。`matched_fields` 列表中的所有字段都必须将 `term_vector` 字段设为 `with_positions_offsets`。合并匹配项的字段是唯一被加载的字段,因此最好将其 `store` 选项设为 `yes`。 + +### 示例 + +为 `shakespeare` 索引创建映射,其中 `text_entry` 字段使用 `standard` 分析器(analyzer)进行分析,并且有一个使用 `english` 分析器进行分析的 `english` 子字段: + +```json +PUT shakespeare +{ + "mappings" : { + "properties" : { + "text_entry" : { + "type" : "text", + "term_vector": "with_positions_offsets", + "fields": { + "english": { + "type": "text", + "analyzer": "english", + "term_vector": "with_positions_offsets" + } + } + } + } + } +} +``` + +`standard` 分析器会将 `text_entry` 字段拆分为单个单词。可以使用 analyze API 操作来确认这一点: + +```json +GET shakespeare/_analyze +{ + "text": "bragging of thine", + "field": "text_entry" +} +``` + +响应中包含按空白拆分后的原始字符串: + +```json +{ + "tokens" : [ + { + "token" : "bragging", + "start_offset" : 0, + "end_offset" : 8, + "type" : "", + "position" : 0 + }, + { + "token" : "of", + "start_offset" : 9, + "end_offset" : 11, + "type" : "", + "position" : 1 + }, + { + "token" : "thine", + "start_offset" : 12, + "end_offset" : 17, + "type" : "", + "position" : 2 + } + ] +} +``` + +`english` 分析器不仅会将字符串拆分为单词,还会对词元(token)进行词干提取并删除停用词。可以对 `text_entry.english` 字段使用 analyze API 操作来确认这一点: + +```json +GET shakespeare/_analyze +{ + "text": "bragging of thine", + "field": "text_entry.english" +} +``` + +响应中包含经过词干提取的单词: + +```json +{ + "tokens" : [ + { + "token" : "brag", + "start_offset" : 0, + "end_offset" : 8, + "type" : "", + "position" : 0 + }, + { + "token" : "thine", + "start_offset" : 12, + "end_offset" : 17, + "type" : "", + "position" : 2 + } + ] +} +``` + +要搜索单词 `bragging` 的所有形式,请使用以下查询: + +```json +GET shakespeare/_search +{ + "query": { + "query_string": { + "query": "text_entry.english:bragging", + "fields": [ + "text_entry" + ] + } + }, + "highlight": { + "order": "score", + "fields": { + "text_entry": { + "matched_fields": [ + "text_entry", + "text_entry.english" + ], + "type": "fvh" + } + } + } +} +``` + +响应在 `text_entry` 字段中高亮显示了单词 "bragging" 的所有形式: + +```json +{ + "took" : 5, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 26, + "relation" : "eq" + }, + "max_score" : 10.153671, + "hits" : [ + { + "_index" : "shakespeare", + "_id" : "56666", + "_score" : 10.153671, + "_source" : { + "type" : "line", + "line_id" : 56667, + "play_name" : "macbeth", + "speech_number" : 34, + "line_number" : "2.3.118", + "speaker" : "MACBETH", + "text_entry" : "Is left this vault to brag of." + }, + "highlight" : { + "text_entry" : [ + "Is left this vault to brag of." + ] + } + }, + { + "_index" : "shakespeare", + "_id" : "71445", + "_score" : 9.284528, + "_source" : { + "type" : "line", + "line_id" : 71446, + "play_name" : "Much Ado about nothing", + "speech_number" : 18, + "line_number" : "5.1.65", + "speaker" : "LEONATO", + "text_entry" : "As under privilege of age to brag" + }, + "highlight" : { + "text_entry" : [ + "As under privilege of age to brag" + ] + } + }, + { + "_index" : "shakespeare", + "_id" : "86782", + "_score" : 9.284528, + "_source" : { + "type" : "line", + "line_id" : 86783, + "play_name" : "Romeo and Juliet", + "speech_number" : 8, + "line_number" : "2.6.31", + "speaker" : "JULIET", + "text_entry" : "Brags of his substance, not of ornament:" + }, + "highlight" : { + "text_entry" : [ + "Brags of his substance, not of ornament:" + ] + } + }, + { + "_index" : "shakespeare", + "_id" : "44531", + "_score" : 8.552448, + "_source" : { + "type" : "line", + "line_id" : 44532, + "play_name" : "King John", + "speech_number" : 15, + "line_number" : "3.1.124", + "speaker" : "CONSTANCE", + "text_entry" : "A ramping fool, to brag and stamp and swear" + }, + "highlight" : { + "text_entry" : [ + "A ramping fool, to brag and stamp and swear" + ] + } + }, + { + "_index" : "shakespeare", + "_id" : "63208", + "_score" : 8.552448, + "_source" : { + "type" : "line", + "line_id" : 63209, + "play_name" : "Merchant of Venice", + "speech_number" : 11, + "line_number" : "3.4.79", + "speaker" : "PORTIA", + "text_entry" : "A thousand raw tricks of these bragging Jacks," + }, + "highlight" : { + "text_entry" : [ + "A thousand raw tricks of these bragging Jacks," + ] + } + }, + { + "_index" : "shakespeare", + "_id" : "73026", + "_score" : 8.552448, + "_source" : { + "type" : "line", + "line_id" : 73027, + "play_name" : "Othello", + "speech_number" : 75, + "line_number" : "2.1.242", + "speaker" : "IAGO", + "text_entry" : "but for bragging and telling her fantastical lies:" + }, + "highlight" : { + "text_entry" : [ + "but for bragging and telling her fantastical lies:" + ] + } + }, + { + "_index" : "shakespeare", + "_id" : "85974", + "_score" : 8.552448, + "_source" : { + "type" : "line", + "line_id" : 85975, + "play_name" : "Romeo and Juliet", + "speech_number" : 20, + "line_number" : "1.5.70", + "speaker" : "CAPULET", + "text_entry" : "And, to say truth, Verona brags of him" + }, + "highlight" : { + "text_entry" : [ + "And, to say truth, Verona brags of him" + ] + } + }, + { + "_index" : "shakespeare", + "_id" : "96800", + "_score" : 8.552448, + "_source" : { + "type" : "line", + "line_id" : 96801, + "play_name" : "Titus Andronicus", + "speech_number" : 60, + "line_number" : "1.1.311", + "speaker" : "SATURNINUS", + "text_entry" : "Agree these deeds with that proud brag of thine," + }, + "highlight" : { + "text_entry" : [ + "Agree these deeds with that proud brag of thine," + ] + } + }, + { + "_index" : "shakespeare", + "_id" : "18189", + "_score" : 7.9273787, + "_source" : { + "type" : "line", + "line_id" : 18190, + "play_name" : "As you like it", + "speech_number" : 12, + "line_number" : "5.2.30", + "speaker" : "ROSALIND", + "text_entry" : "and Caesars thrasonical brag of I came, saw, and" + }, + "highlight" : { + "text_entry" : [ + "and Caesars thrasonical brag of I came, saw, and" + ] + } + }, + { + "_index" : "shakespeare", + "_id" : "32054", + "_score" : 7.9273787, + "_source" : { + "type" : "line", + "line_id" : 32055, + "play_name" : "Cymbeline", + "speech_number" : 52, + "line_number" : "5.5.211", + "speaker" : "IACHIMO", + "text_entry" : "And then a mind put int, either our brags" + }, + "highlight" : { + "text_entry" : [ + "And then a mind put int, either our brags" + ] + } + } + ] + } +} +``` + +要让单词 "bragging" 的原始形式获得更高的评分,可以对 `text_entry` 字段进行权重提升(boost): + +```json +GET shakespeare/_search +{ + "query": { + "query_string": { + "query": "bragging", + "fields": [ + "text_entry^5", + "text_entry.english" + ] + } + }, + "highlight": { + "order": "score", + "fields": { + "text_entry": { + "matched_fields": [ + "text_entry", + "text_entry.english" + ], + "type": "fvh" + } + } + } +} +``` + +响应会首先列出包含单词 "bragging" 的文档: + +```json +{ + "took" : 17, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 26, + "relation" : "eq" + }, + "max_score" : 49.746853, + "hits" : [ + { + "_index" : "shakespeare", + "_id" : "45739", + "_score" : 49.746853, + "_source" : { + "type" : "line", + "line_id" : 45740, + "play_name" : "King John", + "speech_number" : 10, + "line_number" : "5.1.51", + "speaker" : "BASTARD", + "text_entry" : "Of bragging horror: so shall inferior eyes," + }, + "highlight" : { + "text_entry" : [ + "Of bragging horror: so shall inferior eyes," + ] + } + }, + { + "_index" : "shakespeare", + "_id" : "63208", + "_score" : 47.077244, + "_source" : { + "type" : "line", + "line_id" : 63209, + "play_name" : "Merchant of Venice", + "speech_number" : 11, + "line_number" : "3.4.79", + "speaker" : "PORTIA", + "text_entry" : "A thousand raw tricks of these bragging Jacks," + }, + "highlight" : { + "text_entry" : [ + "A thousand raw tricks of these bragging Jacks," + ] + } + }, + { + "_index" : "shakespeare", + "_id" : "68474", + "_score" : 47.077244, + "_source" : { + "type" : "line", + "line_id" : 68475, + "play_name" : "A Midsummer nights dream", + "speech_number" : 101, + "line_number" : "3.2.427", + "speaker" : "PUCK", + "text_entry" : "Thou coward, art thou bragging to the stars," + }, + "highlight" : { + "text_entry" : [ + "Thou coward, art thou bragging to the stars," + ] + } + }, + { + "_index" : "shakespeare", + "_id" : "73026", + "_score" : 47.077244, + "_source" : { + "type" : "line", + "line_id" : 73027, + "play_name" : "Othello", + "speech_number" : 75, + "line_number" : "2.1.242", + "speaker" : "IAGO", + "text_entry" : "but for bragging and telling her fantastical lies:" + }, + "highlight" : { + "text_entry" : [ + "but for bragging and telling her fantastical lies:" + ] + } + }, + { + "_index" : "shakespeare", + "_id" : "39816", + "_score" : 44.679565, + "_source" : { + "type" : "line", + "line_id" : 39817, + "play_name" : "Henry V", + "speech_number" : 28, + "line_number" : "5.2.138", + "speaker" : "KING HENRY V", + "text_entry" : "armour on my back, under the correction of bragging" + }, + "highlight" : { + "text_entry" : [ + "armour on my back, under the correction of bragging" + ] + } + }, + { + "_index" : "shakespeare", + "_id" : "63200", + "_score" : 44.679565, + "_source" : { + "type" : "line", + "line_id" : 63201, + "play_name" : "Merchant of Venice", + "speech_number" : 11, + "line_number" : "3.4.71", + "speaker" : "PORTIA", + "text_entry" : "Like a fine bragging youth, and tell quaint lies," + }, + "highlight" : { + "text_entry" : [ + "Like a fine bragging youth, and tell quaint lies," + ] + } + }, + { + "_index" : "shakespeare", + "_id" : "56666", + "_score" : 10.153671, + "_source" : { + "type" : "line", + "line_id" : 56667, + "play_name" : "macbeth", + "speech_number" : 34, + "line_number" : "2.3.118", + "speaker" : "MACBETH", + "text_entry" : "Is left this vault to brag of." + }, + "highlight" : { + "text_entry" : [ + "Is left this vault to brag of." + ] + } + }, + { + "_index" : "shakespeare", + "_id" : "71445", + "_score" : 9.284528, + "_source" : { + "type" : "line", + "line_id" : 71446, + "play_name" : "Much Ado about nothing", + "speech_number" : 18, + "line_number" : "5.1.65", + "speaker" : "LEONATO", + "text_entry" : "As under privilege of age to brag" + }, + "highlight" : { + "text_entry" : [ + "As under privilege of age to brag" + ] + } + }, + { + "_index" : "shakespeare", + "_id" : "86782", + "_score" : 9.284528, + "_source" : { + "type" : "line", + "line_id" : 86783, + "play_name" : "Romeo and Juliet", + "speech_number" : 8, + "line_number" : "2.6.31", + "speaker" : "JULIET", + "text_entry" : "Brags of his substance, not of ornament:" + }, + "highlight" : { + "text_entry" : [ + "Brags of his substance, not of ornament:" + ] + } + }, + { + "_index" : "shakespeare", + "_id" : "44531", + "_score" : 8.552448, + "_source" : { + "type" : "line", + "line_id" : 44532, + "play_name" : "King John", + "speech_number" : 15, + "line_number" : "3.1.124", + "speaker" : "CONSTANCE", + "text_entry" : "A ramping fool, to brag and stamp and swear" + }, + "highlight" : { + "text_entry" : [ + "A ramping fool, to brag and stamp and swear" + ] + } + } + ] + } +} +``` + +## 查询限制 + +请注意以下限制: + +- 在提取要高亮的词项时,高亮器不会反映查询的布尔逻辑。因此,对于某些复杂的布尔查询,例如嵌套布尔查询和使用 `minimum_should_match` 的查询,OpenSearch 可能会高亮与查询匹配项不对应的词项。 +- `fvh` 高亮器不支持跨度查询(span query)。 diff --git a/i18n/zh/search-plugins/searching-data/index.md b/i18n/zh/search-plugins/searching-data/index.md new file mode 100644 index 00000000..2d9f4007 --- /dev/null +++ b/i18n/zh/search-plugins/searching-data/index.md @@ -0,0 +1,15 @@ +--- +title: 搜索数据 +--- + +# 搜索数据 + +多年来,用户对搜索引擎的期望不断提高。对大多数用户来说,仅仅快速返回相关结果已经不够了。现在,用户希望能获得相关性更高的结果,能够对结果进行排序和组织,并能高亮显示查询内容。OpenSearch 提供了许多增强搜索体验的功能,如下表所示。 + +功能 | 描述 +:--- | :--- +[自动补全(autocomplete)功能](/search-plugins/searching-data/autocomplete) | 在用户输入时建议短语。 +[拼写纠错(did-you-mean)功能](/search-plugins/searching-data/did-you-mean) | 在用户输入时检查短语的拼写。 +[分页显示结果](/search-plugins/searching-data/paginate) | 将搜索结果分成多页显示,而不是显示为一个很长的列表。 +[对结果排序](/search-plugins/searching-data/sort) | 允许按不同条件对结果进行排序(sort)。 +[高亮显示查询匹配项](/search-plugins/searching-data/highlight) | 在结果中高亮(highlighting)显示搜索词。 diff --git a/i18n/zh/search-plugins/searching-data/paginate.md b/i18n/zh/search-plugins/searching-data/paginate.md new file mode 100644 index 00000000..afbde379 --- /dev/null +++ b/i18n/zh/search-plugins/searching-data/paginate.md @@ -0,0 +1,275 @@ +--- +title: 分页显示结果 +--- + +## 分页显示结果 + +在 OpenSearch 中,可以使用以下方法对搜索结果进行分页(pagination): + +1. [`from` 和 `size` 参数](#the-from-and-size-parameters) +1. [滚动搜索](#scroll-search)操作 +1. [`search_after` 参数](#the-search_after-parameter) +1. [时间点与 `search_after` 结合使用](#point-in-time-with-search_after) + +## `from` 和 `size` 参数 + +`from` 和 `size` 参数每次返回一页结果。 + +`from` 参数是开始显示结果的文档序号,`size` 参数是要显示的结果数量。两者结合使用,即可返回搜索结果的一个子集。 + +例如,如果 `size` 的值为 10,`from` 的值为 0,就会看到前 10 个结果。如果把 `from` 的值改为 10,就会看到接下来的 10 个结果(因为结果从 0 开始编号)。因此,如果要从第 11 个结果开始查看,`from` 必须为 10。 + +```json +GET shakespeare/_search +{ + "from": 0, + "size": 10, + "query": { + "match": { + "play_name": "Hamlet" + } + } +} +``` + +使用以下公式,根据页码计算 `from` 参数: + +```json +from = size * (page_number - 1) +``` + +用户每次选择下一页结果时,应用程序都需要使用递增后的 `from` 值重新运行同一个搜索查询。 + +也可以在搜索 URI 中指定 `from` 和 `size` 参数: + +```json +GET shakespeare/_search?from=0&size=10 +``` + +如果只指定了 `size` 参数,`from` 参数默认为 0。 + +查询结果中很靠后的页面会对性能产生显著影响,因此 OpenSearch 将这种方法限制在 10,000 个结果以内。 + +`from` 和 `size` 参数是无状态的,因此结果基于最新的可用数据。 +这可能导致分页结果不一致。 +例如,假设用户停留在结果的第一页,随后翻到第二页。在此期间,一个与用户搜索相关的新文档被索引,并出现在第一页上。这种情况下,第一页的最后一个结果会被挤到第二页,用户就会看到重复的结果(也就是说,第一页和第二页都显示了这个结果)。 + +如需一致的分页,请使用 `scroll` 操作。`scroll` 操作会在一段时间内保持搜索上下文(search context)处于打开状态,在此期间,任何数据变更都不会影响结果。 + +## 滚动搜索 + +`from` 和 `size` 参数可以对搜索结果进行分页,但每次最多只能返回 10,000 个结果。 + +如果需要请求大于 1 PB 的数据量(例如用于机器学习作业),请改用 `scroll` 操作。`scroll` 操作允许请求数量不限的结果。 + +要使用滚动操作,请在请求头中添加 `scroll` 参数,并指定一个搜索上下文,告诉 OpenSearch 需要保持滚动多长时间。该搜索上下文的时长需要足以处理一批结果。 + +要设置每批返回的结果数量,请使用 `size` 参数: + +```json +GET shakespeare/_search?scroll=10m +{ + "size": 10000 +} +``` + +OpenSearch 会缓存结果并返回一个滚动 ID,可以使用它分批访问这些结果: + +```json +"_scroll_id" : "DXF1ZXJ5QW5kRmV0Y2gBAAAAAAAAAAUWdmpUZDhnRFBUcWFtV21nMmFwUGJEQQ==" +``` + +将此滚动 ID 传给 `scroll` 操作,即可获取下一批结果: + +```json +GET _search/scroll +{ + "scroll": "10m", + "scroll_id": "DXF1ZXJ5QW5kRmV0Y2gBAAAAAAAAAAUWdmpUZDhnRFBUcWFtV21nMmFwUGJEQQ==" +} +``` + +只要搜索上下文仍处于打开状态,就可以使用此滚动 ID 以每批 10,000 个的方式获取结果。通常,滚动 ID 在请求之间不会改变,但它*有可能*改变,因此请务必始终使用最新的滚动 ID。如果没有在设置的搜索上下文时间内发送下一个滚动请求,`scroll` 操作将不会返回任何结果。 + +如果预计会有数十亿个结果,请使用切片滚动(sliced scroll)。切片允许对同一个请求并行执行多个滚动操作。 +设置滚动的 ID 和最大切片数: + +```json +GET shakespeare/_search?scroll=10m +{ + "slice": { + "id": 0, + "max": 10 + }, + "query": { + "match_all": {} + } +} +``` + +使用单个滚动 ID,会收到 10 个结果。 +最多可以有 10 个 ID。 +将 ID 设为 1,执行同样的命令: + +```json +GET shakespeare/_search?scroll=10m +{ + "slice": { + "id": 1, + "max": 10 + }, + "query": { + "match_all": {} + } +} +``` + +滚动完成后请关闭搜索上下文,因为它在超时之前会一直占用计算资源: + +```json +DELETE _search/scroll/DXF1ZXJ5QW5kRmV0Y2gBAAAAAAAAAAcWdmpUZDhnRFBUcWFtV21nMmFwUGJEQQ== +``` + +#### 示例响应 + +```json +{ + "succeeded": true, + "num_freed": 1 +} +``` + +使用以下请求关闭所有打开的滚动上下文: + +```json +DELETE _search/scroll/_all +``` + +`scroll` 操作对应于一个特定的时间戳,不会将该时间戳之后添加的文档视为潜在结果。 + +由于打开的搜索上下文会消耗大量内存,对于不需要保持搜索上下文打开的频繁用户查询,建议不要使用 `scroll` 操作,而是将 `sort` 参数与 `search_after` 参数结合使用,来滚动用户查询的响应。 + +## `search_after` 参数 {#the-searchafter-parameter} + +`search_after` 参数提供了一个实时游标(cursor),使用上一页的结果来获取下一页的结果。它与 `scroll` 操作类似,目的是并行滚动多个查询。 + +例如,以下查询按台词编号(speech number)、再按 ID 对剧作 "Hamlet" 中的所有台词进行排序(sort),并检索前三个结果: + +```json +GET shakespeare/_search +{ + "size": 3, + "query": { + "match": { + "play_name": "Hamlet" + } + }, + "sort": [ + { "speech_number": "asc" }, + { "_id": "asc" } + ] +} +``` + +响应中包含每个文档的 `sort` 值数组: + +```json +{ + "took" : 7, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 4244, + "relation" : "eq" + }, + "max_score" : null, + "hits" : [ + { + "_index" : "shakespeare", + "_id" : "32435", + "_score" : null, + "_source" : { + "type" : "line", + "line_id" : 32436, + "play_name" : "Hamlet", + "speech_number" : 1, + "line_number" : "1.1.1", + "speaker" : "BERNARDO", + "text_entry" : "Whos there?" + }, + "sort" : [ + 1, + "32435" + ] + }, + { + "_index" : "shakespeare", + "_id" : "32634", + "_score" : null, + "_source" : { + "type" : "line", + "line_id" : 32635, + "play_name" : "Hamlet", + "speech_number" : 1, + "line_number" : "1.2.1", + "speaker" : "KING CLAUDIUS", + "text_entry" : "Though yet of Hamlet our dear brothers death" + }, + "sort" : [ + 1, + "32634" + ] + }, + { + "_index" : "shakespeare", + "_id" : "32635", + "_score" : null, + "_source" : { + "type" : "line", + "line_id" : 32636, + "play_name" : "Hamlet", + "speech_number" : 1, + "line_number" : "1.2.2", + "speaker" : "KING CLAUDIUS", + "text_entry" : "The memory be green, and that it us befitted" + }, + "sort" : [ + 1, + "32635" + ] + } + ] + } +} +``` + +可以使用最后一个结果的 `sort` 值,通过 `search_after` 参数检索后续结果: + +```json +GET shakespeare/_search +{ + "size": 10, + "query": { + "match": { + "play_name": "Hamlet" + } + }, + "search_after": [ 1, "32635"], + "sort": [ + { "speech_number": "asc" }, + { "_id": "asc" } + ] +} +``` + +与 `scroll` 操作不同,`search_after` 参数是无状态的,因此文档顺序可能会因为文档被索引或删除而发生变化。 + +## 时间点与 `search_after` 结合使用 {#point-in-time-with-searchafter} + +时间点(Point in Time,PIT)与 `search_after` 结合使用是 OpenSearch 中首选的分页方法,尤其适用于深度分页。它可以绕开其他所有方法的限制,因为它操作的是冻结在某一时刻的数据集,不绑定到某个查询,并且支持向前和向后的一致分页。要了解更多信息,请参阅[时间点](/search-plugins/searching-data/point-in-time)。 diff --git a/i18n/zh/search-plugins/searching-data/point-in-time-api.md b/i18n/zh/search-plugins/searching-data/point-in-time-api.md new file mode 100644 index 00000000..863ad114 --- /dev/null +++ b/i18n/zh/search-plugins/searching-data/point-in-time-api.md @@ -0,0 +1,261 @@ +--- +title: Point in Time API +--- + +# Point in Time API + +使用 [时间点(Point in Time,PIT)](/search-plugins/searching-data/point-in-time) API 管理 PIT。 + +--- + +#### 目录 +- TOC + +--- + +## 创建 PIT + + +创建一个 PIT。`keep_alive` 查询参数是必需的,它指定 PIT 的保留时长。 + +### 路径和 HTTP 方法 + +```json +POST //_search/point_in_time?keep_alive=1h&routing=&expand_wildcards=&preference= +``` + +### 路径参数 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +target_indexes | String | PIT 的目标索引名称。可以是以逗号分隔的列表,也可以是通配符索引模式。 + +### 查询参数 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +keep_alive | Time | PIT 的保留时长。每次通过 Search API 访问 PIT 时,PIT 的生命周期都会延长 `keep_alive` 参数所指定的时长。必需。 +preference | String | 用于执行搜索的节点或分片(shard)。可选。默认值为随机。 +routing | String | 指定将搜索请求路由到特定分片。可选。默认值为文档的 `_id`。 +expand_wildcards | String | 可与通配符模式匹配的索引类型。支持以逗号分隔的多个值。有效值如下:
- `all`:匹配任意索引或数据流,包括隐藏的索引或数据流。
- `open`:匹配打开的、非隐藏的索引或非隐藏的数据流。
- `closed`:匹配关闭的、非隐藏的索引或非隐藏的数据流。
- `hidden`:匹配隐藏的索引或数据流。必须与 `open`、`closed` 或者同时与 `open` 和 `closed` 组合使用。
- `none`:不接受任何通配符模式。
可选。默认值为 `open`。 +allow_partial_pit_creation | Boolean | 指定在部分失败时是否仍创建 PIT。可选。默认值为 `true`。 + +#### 示例请求 + +```json +POST /my-index-1/_search/point_in_time?keep_alive=100m +``` + +#### 示例响应 + +```json +{ + "pit_id": "o463QQEPbXktaW5kZXgtMDAwMDAxFnNOWU43ckt3U3IyaFVpbGE1UWEtMncAFjFyeXBsRGJmVFM2RTB6eVg1aVVqQncAAAAAAAAAAAIWcDVrM3ZIX0pRNS1XejE5YXRPRFhzUQEWc05ZTjdyS3dTcjJoVWlsYTVRYS0ydwAA", + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "creation_time": 1658146050064 +} +``` + +### 响应字段 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +pit_id | [Base64 encoded binary](/field-types/supported-field-types/binary) | PIT ID。 +creation_time | long | PIT 的创建时间,以自纪元(epoch)以来的毫秒数表示。 + +## 延长 PIT 时间 + +执行搜索时,可以在 `pit` 对象中提供 `keep_alive` 参数来延长 PIT 时间: + +```json +GET /_search +{ + "size": 10000, + "query": { + "match" : { + "user.id" : "elkbee" + } + }, + "pit": { + "id": "46ToAwMDaWR5BXV1aWQyKwZub2RlXzMAAAAAAAAAACoBYwADaWR4BXV1aWQxAgZub2RlXzEAAAAAAAAAAAEBYQADaWR5BXV1aWQyKgZub2RlXzIAAAAAAAAAAAwBYgACBXV1aWQyAAAFdXVpZDEAAQltYXRjaF9hbGw_gAAAAA==", + "keep_alive": "100m" + }, + "sort": [ + {"@timestamp": {"order": "asc"}} + ], + "search_after": [ + "2021-05-20T05:30:04.832Z" + ] +} +``` + +::: info 注意 +搜索请求中的 `keep_alive` 参数是可选的,它指定 PIT 保留时间的延长量。 +::: + +## 列出所有 PIT + + +返回 OpenSearch 集群中的所有 PIT。 + +### 跨集群行为 + +List All PITs API 只返回本地 PIT 或混合 PIT(同时在本地集群和远程集群中创建的 PIT),不返回完全位于远程的 PIT。 + +#### 示例请求 {#example-request-1} + +```json +GET /_search/point_in_time/_all +``` + +#### 示例响应 {#example-response-1} + +```json +{ + "pits": [ + { + "pit_id": "o463QQEPbXktaW5kZXgtMDAwMDAxFnNOWU43ckt3U3IyaFVpbGE1UWEtMncAFjFyeXBsRGJmVFM2RTB6eVg1aVVqQncAAAAAAAAAAAEWcDVrM3ZIX0pRNS1XejE5YXRPRFhzUQEWc05ZTjdyS3dTcjJoVWlsYTVRYS0ydwAA", + "creation_time": 1658146048666, + "keep_alive": 6000000 + }, + { + "pit_id": "o463QQEPbXktaW5kZXgtMDAwMDAxFnNOWU43ckt3U3IyaFVpbGE1UWEtMncAFjFyeXBsRGJmVFM2RTB6eVg1aVVqQncAAAAAAAAAAAIWcDVrM3ZIX0pRNS1XejE5YXRPRFhzUQEWc05ZTjdyS3dTcjJoVWlsYTVRYS0ydwAA", + "creation_time": 1658146050064, + "keep_alive": 6000000 + } + ] +} +``` + +### 响应字段 {#response-fields-1} + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +pits | Array of JSON objects | 所有 PIT 的列表。 + +每个 PIT 对象包含以下字段。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +pit_id | [Base64 encoded binary](/field-types/supported-field-types/binary) | PIT ID。 +creation_time | long | PIT 的创建时间,以自纪元以来的毫秒数表示。 +keep_alive | long | PIT 的保留时长,以毫秒为单位。 + +## 删除 PIT + + +删除一个、多个或全部 PIT。`keep_alive` 时间段结束后,PIT 会被自动删除。不过,为了释放资源,也可以使用 Delete PIT API 删除 PIT。Delete PIT API 支持按 ID 删除一组 PIT,或一次性删除所有 PIT。 + +### 跨集群行为 {#cross-cluster-behavior-1} + +Delete PITs by ID API 完全支持删除跨集群 PIT。 + +Delete All PITs API 只删除本地 PIT 或混合 PIT(同时在本地集群和远程集群中创建的 PIT),不删除完全位于远程的 PIT。 + +#### 示例请求:删除所有 PIT + +```json +DELETE /_search/point_in_time/_all +``` + +如果要删除一个或多个 PIT,请在请求正文中指定它们的 PIT ID。 + +### 请求字段 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +pit_id | [Base64 encoded binary](/field-types/supported-field-types/binary) or an array of binaries | 要删除的 PIT 的 ID。必需。 + +#### 示例请求:按 ID 删除 PIT + +```json +DELETE /_search/point_in_time + +{ + "pit_id": [ + "o463QQEPbXktaW5kZXgtMDAwMDAxFkhGN09fMVlPUkVPLXh6MUExZ1hpaEEAFjBGbmVEZHdGU1EtaFhhUFc4ZkR5cWcAAAAAAAAAAAEWaXBPNVJtZEhTZDZXTWFFR05waXdWZwEWSEY3T18xWU9SRU8teHoxQTFnWGloQQAA", + "o463QQEPbXktaW5kZXgtMDAwMDAxFkhGN09fMVlPUkVPLXh6MUExZ1hpaEEAFjBGbmVEZHdGU1EtaFhhUFc4ZkR5cWcAAAAAAAAAAAIWaXBPNVJtZEhTZDZXTWFFR05waXdWZwEWSEY3T18xWU9SRU8teHoxQTFnWGloQQAA" + ] +} +``` + +#### 示例响应 {#example-response-2} + +对于每个 PIT,响应中都包含一个 JSON 对象,其中有 PIT ID 和一个 `successful` 字段,用于表示删除是否成功。部分失败按失败处理。 + +```json +{ + "pits": [ + { + "successful": true, + "pit_id": "o463QQEPbXktaW5kZXgtMDAwMDAxFkhGN09fMVlPUkVPLXh6MUExZ1hpaEEAFjBGbmVEZHdGU1EtaFhhUFc4ZkR5cWcAAAAAAAAAAAEWaXBPNVJtZEhTZDZXTWFFR05waXdWZwEWSEY3T18xWU9SRU8teHoxQTFnWGloQQAA" + }, + { + "successful": false, + "pit_id": "o463QQEPbXktaW5kZXgtMDAwMDAxFkhGN09fMVlPUkVPLXh6MUExZ1hpaEEAFjBGbmVEZHdGU1EtaFhhUFc4ZkR5cWcAAAAAAAAAAAIWaXBPNVJtZEhTZDZXTWFFR05waXdWZwEWSEY3T18xWU9SRU8teHoxQTFnWGloQQAA" + } + ] +} +``` + +### 响应字段 {#response-fields-2} + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +successful | Boolean | 删除操作是否成功。 +pit_id | [Base64 encoded binary](/field-types/supported-field-types/binary) | 要删除的 PIT 的 ID。 + +## PIT 段 + + +与 [CAT Segments API](/api-reference/cat/cat-segments) 类似,PIT Segments API 通过描述 PIT 的 Lucene 段(segment),提供有关 PIT 磁盘使用情况的底层信息。PIT Segments API 支持按 ID 列出特定 PIT 的段信息,或一次性列出所有 PIT 的段信息。 + +#### 示例请求:所有 PIT 的 PIT 段 + +```json +GET /_cat/pit_segments/_all +``` + +如果要列出一个或多个 PIT 的段,请在请求正文中指定它们的 PIT ID。 + +### 请求字段 {#request-fields-1} + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +pit_id | [Base64 encoded binary](/field-types/supported-field-types/binary) or an array of binaries | 要列出其段的 PIT 的 ID。必需。 + +#### 示例请求:按 ID 列出 PIT 的段 + +```json +GET /_cat/pit_segments + +{ + "pit_id": [ + "o463QQEPbXktaW5kZXgtMDAwMDAxFkhGN09fMVlPUkVPLXh6MUExZ1hpaEEAFjBGbmVEZHdGU1EtaFhhUFc4ZkR5cWcAAAAAAAAAAAEWaXBPNVJtZEhTZDZXTWFFR05waXdWZwEWSEY3T18xWU9SRU8teHoxQTFnWGloQQAA", + "o463QQEPbXktaW5kZXgtMDAwMDAxFkhGN09fMVlPUkVPLXh6MUExZ1hpaEEAFjBGbmVEZHdGU1EtaFhhUFc4ZkR5cWcAAAAAAAAAAAIWaXBPNVJtZEhTZDZXTWFFR05waXdWZwEWSEY3T18xWU9SRU8teHoxQTFnWGloQQAA" + ] +} +``` + +#### 示例响应 {#example-response-3} + +```json +index shard prirep ip segment generation docs.count docs.deleted size size.memory committed searchable version compound +index1 0 r 10.212.36.190 _0 0 4 0 3.8kb 1364 false true 8.8.2 true +index1 1 p 10.212.36.190 _0 0 3 0 3.7kb 1364 false true 8.8.2 true +index1 2 r 10.212.74.139 _0 0 2 0 3.6kb 1364 false true 8.8.2 true +``` + +## PIT 设置 + +可以为 PIT 指定以下设置。 + +设置 | 描述 | 默认值 +:--- | :--- | :--- +point_in_time.max_keep_alive | 集群级设置,指定 `keep_alive` 参数的最大值。 | 24h +search.max_open_pit_context | 节点级设置,指定节点上打开的 PIT 上下文的最大数量。 | 300 diff --git a/i18n/zh/search-plugins/searching-data/point-in-time.md b/i18n/zh/search-plugins/searching-data/point-in-time.md new file mode 100644 index 00000000..d30fb198 --- /dev/null +++ b/i18n/zh/search-plugins/searching-data/point-in-time.md @@ -0,0 +1,152 @@ +--- +title: 时间点 +--- + +# 时间点 + +时间点(Point in Time,PIT)可以让你针对一个固定在某一时刻的数据集运行不同的查询(Query)。 + +通常情况下,如果对一个索引(Index)多次运行同一查询,由于文档(Document)在不断地被索引、更新和删除,同一查询可能会返回不同的结果。如果需要针对相同的数据运行查询,可以通过创建 PIT 来保留该数据的状态。PIT 功能的主要用途是与 `search_after` 功能结合使用,对搜索结果进行深度分页(pagination)。 + +## 对搜索结果分页 + +除了 PIT 功能之外,OpenSearch 中还有三种[对搜索结果分页](/search-plugins/searching-data/paginate)的方法:使用 Scroll API、在搜索中指定 `from` 和 `size` 参数,以及使用 `search_after` 功能。但这三种方法都有局限性: + +- Scroll API 的搜索结果会冻结在请求发出的那一刻,但它们与特定的查询绑定。此外,scroll 在搜索中只能向前移动,因此如果某一页的请求失败,后续请求会跳过该页并返回下一页。 +- 如果在搜索中指定 `from` 和 `size` 参数,搜索结果不会冻结在某个时间点,因此可能会因为文档的索引或删除而不一致。不建议将 `from` 和 `size` 功能用于深度分页,因为每次请求一页都需要处理所有结果,再从中筛选出所请求的页。 +- `search_after` 的搜索结果不会冻结在某个时间点,因此可能会因为并发的文档索引或删除而不一致。 + +PIT 功能没有其他分页方法的这些局限,因为 PIT 搜索不与查询绑定,并且支持向前和向后的一致性分页。如果你已经查看了结果的第一页,现在位于第二页,那么返回时看到的仍是相同的第一页。 + +## PIT 搜索 + +PIT 搜索具有与常规搜索相同的能力,区别在于 PIT 搜索作用于较旧的数据集,而常规搜索作用于实时数据集。PIT 搜索不与查询绑定,因此可以在同一个冻结于某一时刻的数据集上运行不同的查询。 + +可以使用[创建 PIT API](/search-plugins/searching-data/point-in-time-api#create-a-pit) 来创建 PIT。为一组索引创建 PIT 时,OpenSearch 会锁定这些索引的一组段(Segment),将其冻结在该时刻。在更底层,该 PIT 所需的任何资源都不会被修改或删除。如果属于某个 PIT 的段被合并,OpenSearch 会在创建 PIT 时由 `keep_alive` 参数指定的时间段内保留这些段的副本。 + +创建 PIT 操作会返回一个 PIT ID,你可以用它在冻结的数据集上运行多个查询。即使索引继续摄取数据、修改或删除文档,PIT 引用的仍是自 PIT 创建以来未发生变化的数据。当查询中包含 PIT ID 时,无需在搜索中传入索引,因为搜索会使用该 PIT。使用 PIT ID 的搜索在多次运行时会产生完全相同的结果。 + +::: info 注意 +如果发生集群或节点故障,所有 PIT 数据都会丢失。 +::: + +## 使用 PIT 和 search_after 进行分页 {#pagination-with-pit-and-searchafter} + +使用 PIT ID 运行查询时,可以使用 `search_after` 参数获取下一页结果。这样你就可以控制结果页中文档的顺序。 + +使用 PIT ID 运行搜索查询: + +```json +GET /_search +{ + "size": 10000, + "query": { + "match" : { + "user.id" : "elkbee" + } + }, + "pit": { + "id": "46ToAwMDaWR5BXV1aWQyKwZub2RlXzMAAAAAAAAAACoBYwADaWR4BXV1aWQxAgZub2RlXzEAAAAAAAAAAAEBYQADaWR5BXV1aWQyKgZub2RlXzIAAAAAAAAAAAwBYgACBXV1aWQyAAAFdXVpZDEAAQltYXRjaF9hbGw_gAAAAA==", + "keep_alive": "100m" + }, + "sort": [ + {"@timestamp": {"order": "asc"}} + ] +} +``` + +响应包含与查询匹配的前 10,000 个文档。要获取下一组文档,请运行相同的查询,将最后一个文档的排序值作为 `search_after` 参数,并保持相同的 `sort` 和 `pit.id`。可以使用可选的 `keep_alive` 参数延长 PIT 的保留时间: + +```json +GET /_search +{ + "size": 10000, + "query": { + "match" : { + "user.id" : "elkbee" + } + }, + "pit": { + "id": "46ToAwMDaWR5BXV1aWQyKwZub2RlXzMAAAAAAAAAACoBYwADaWR4BXV1aWQxAgZub2RlXzEAAAAAAAAAAAEBYQADaWR5BXV1aWQyKgZub2RlXzIAAAAAAAAAAAwBYgACBXV1aWQyAAAFdXVpZDEAAQltYXRjaF9hbGw_gAAAAA==", + "keep_alive": "100m" + }, + "sort": [ + {"@timestamp": {"order": "asc"}} + ], + "search_after": [ + "2021-05-20T05:30:04.832Z" + ] +} +``` + +## 搜索切片 + +将 `search_after` 与 PIT 结合用于分页,可以控制结果的排序。如果不需要结果按特定顺序排列,或者希望能够从某一页跳到不连续的另一页,可以使用搜索切片。搜索切片会将一个 PIT 搜索拆分为多个切片,客户端应用程序可以独立地消费这些切片。 + +例如,如果某个 PIT 搜索查询有 1,000,000 个结果,而你希望每次返回 50,000 个结果,那么客户端应用程序需要连续调用 20 次才能接收每一批结果。如果使用搜索切片,就可以并行执行这 20 次调用。在多线程客户端应用程序中,可以为每个 PIT 使用 5 个切片。这样,你将得到 5 个各含 10,000 个命中(hit)的切片,可以由客户端中的 5 个不同线程分别消费,而不是由单个线程消费 50,000 个结果。 + +要使用搜索切片,必须指定两个参数: +- `slice.id` 是所请求切片的 ID。 +- `slice.max` 是将搜索响应拆分成的切片数量。 + +以下 PIT 搜索查询演示了搜索切片: + +```json + +GET /_search +{ + "slice": { + "id": 0, // id 是所请求的切片(页)编号。每次请求只能查询一个切片 + "max": 2 // max 是搜索响应将被拆分成的切片(页)总数 + }, + "query": { + "match": { + "message": "foo" + } + }, + "pit": { + "id": "46ToAwMDaWR5BXV1aWQyKwZub2RlXzMAAAAAAAAAACoBYwADaWR4BXV1aWQxAgZub2RlXzEAAAAAAAAAAAEBYQADaWR5BXV1aWQyKgZub2RlXzIAAAAAAAAAAAwBYgACBXV1aWQyAAAFdXVpZDEAAQltYXRjaF9hbGw_gAAAAA==" + } +} +``` + +每次请求只能查询一个切片,因此下一个查询与上一个查询相同,只是 `slice.id` 为 `1`。 + +## 安全模型 + +本节介绍在启用 Security 插件(plugin)运行 OpenSearch 时,使用 PIT API 操作所需的权限(permission)。 + +用户可以通过 `point_in_time_full_access` 角色(role)访问所有 PIT API 操作。如果该角色不能满足你的需求,可以根据使用场景组合各个 PIT 权限。每个操作都对应 REST API 中的一个操作。例如,`indices:data/read/point_in_time/create` 权限允许你创建 PIT。可用的权限如下: + +- `indices:data/read/point_in_time/create` – 创建 API +- `indices:data/read/point_in_time/delete` – 删除 API +- `indices:data/read/point_in_time/readall` – 列出所有 PIT API +- `indices:data/read/search` – 搜索 API +- `indices:monitor/point_in_time/segments` – PIT 段 API + +对于 `all` 类 API 操作(例如列出全部和删除全部),用户需要拥有所有索引(*)的权限。对于搜索、创建 PIT 或删除列表等 API 操作,用户只需拥有单个索引的权限。 + +PIT ID 在保存时始终包含底层(已解析的)索引。以下各节介绍别名(Alias)和数据流所需的权限。 + +### 别名权限 + +对于别名,用户必须拥有索引权限**或**别名权限,才能执行任何 PIT 操作。 + +### 数据流权限 + +对于数据流,用户必须同时拥有数据流权限**和**该数据流的后备索引权限,才能执行任何 PIT 操作。例如,用户必须拥有 `data-stream-11` 数据流及其后备索引 `.ds-my-data-stream11-000001` 的权限。 + +如果用户只有数据流权限,则可以创建 PIT,但在没有后备索引权限的情况下,无法将 PIT ID 用于搜索等其他操作。 + +## API + +下表列出了所有[时间点 API](/search-plugins/searching-data/point-in-time-api) 函数。 + +函数 | API | 说明 +:--- | :--- | :--- +[创建 PIT](/search-plugins/searching-data/point-in-time-api#create-a-pit) | `POST //_search/point_in_time?keep_alive=1h` | 创建 PIT。 +[列出 PIT](/search-plugins/searching-data/point-in-time-api#list-all-pits) | `GET /_search/point_in_time/_all` | 列出所有 PIT。 +[删除 PIT](/search-plugins/searching-data/point-in-time-api#delete-pits) | `DELETE /_search/point_in_time`
`DELETE /_search/point_in_time/_all` | 删除一个 PIT 或所有 PIT。 +[PIT 段](/search-plugins/searching-data/point-in-time-api#pit-segments) | `GET /_cat/pit_segments/_all` | 通过描述 PIT 的 Lucene 段,提供有关该 PIT 磁盘使用情况的信息。 + +有关相关的集群和节点设置,请参阅 [PIT 设置](/search-plugins/searching-data/point-in-time-api#pit-settings)。 diff --git a/i18n/zh/search-plugins/searching-data/sort.md b/i18n/zh/search-plugins/searching-data/sort.md new file mode 100644 index 00000000..96202fb8 --- /dev/null +++ b/i18n/zh/search-plugins/searching-data/sort.md @@ -0,0 +1,879 @@ +--- +title: 对结果排序 +--- + +## 对结果排序 + +排序(sort)可以让用户按照对他们最有意义的方式对结果进行排序。 + +默认情况下,全文查询(full-text query)按相关性评分(Relevance Score)对结果排序。 +通过将 `order` 参数设置为 `asc` 或 `desc`,可以按任意字段(Field)值以升序或降序对结果进行排序。 + +例如,要按 `line_id` 值的降序对结果排序,请使用以下查询: + +```json +GET shakespeare/_search +{ + "query": { + "term": { + "play_name": { + "value": "Henry IV" + } + } + }, + "sort": [ + { + "line_id": { + "order": "desc" + } + } + ] +} +``` + +结果按 `line_id` 降序排列: + +```json +{ + "took" : 24, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 3205, + "relation" : "eq" + }, + "max_score" : null, + "hits" : [ + { + "_index" : "shakespeare", + "_id" : "3204", + "_score" : null, + "_source" : { + "type" : "line", + "line_id" : 3205, + "play_name" : "Henry IV", + "speech_number" : 8, + "line_number" : "", + "speaker" : "KING HENRY IV", + "text_entry" : "Exeunt" + }, + "sort" : [ + 3205 + ] + }, + { + "_index" : "shakespeare", + "_id" : "3203", + "_score" : null, + "_source" : { + "type" : "line", + "line_id" : 3204, + "play_name" : "Henry IV", + "speech_number" : 8, + "line_number" : "5.5.45", + "speaker" : "KING HENRY IV", + "text_entry" : "Let us not leave till all our own be won." + }, + "sort" : [ + 3204 + ] + }, + { + "_index" : "shakespeare", + "_id" : "3202", + "_score" : null, + "_source" : { + "type" : "line", + "line_id" : 3203, + "play_name" : "Henry IV", + "speech_number" : 8, + "line_number" : "5.5.44", + "speaker" : "KING HENRY IV", + "text_entry" : "And since this business so fair is done," + }, + "sort" : [ + 3203 + ] + }, + { + "_index" : "shakespeare", + "_id" : "3201", + "_score" : null, + "_source" : { + "type" : "line", + "line_id" : 3202, + "play_name" : "Henry IV", + "speech_number" : 8, + "line_number" : "5.5.43", + "speaker" : "KING HENRY IV", + "text_entry" : "Meeting the cheque of such another day:" + }, + "sort" : [ + 3202 + ] + }, + { + "_index" : "shakespeare", + "_id" : "3200", + "_score" : null, + "_source" : { + "type" : "line", + "line_id" : 3201, + "play_name" : "Henry IV", + "speech_number" : 8, + "line_number" : "5.5.42", + "speaker" : "KING HENRY IV", + "text_entry" : "Rebellion in this land shall lose his sway," + }, + "sort" : [ + 3201 + ] + }, + { + "_index" : "shakespeare", + "_id" : "3199", + "_score" : null, + "_source" : { + "type" : "line", + "line_id" : 3200, + "play_name" : "Henry IV", + "speech_number" : 8, + "line_number" : "5.5.41", + "speaker" : "KING HENRY IV", + "text_entry" : "To fight with Glendower and the Earl of March." + }, + "sort" : [ + 3200 + ] + }, + { + "_index" : "shakespeare", + "_id" : "3198", + "_score" : null, + "_source" : { + "type" : "line", + "line_id" : 3199, + "play_name" : "Henry IV", + "speech_number" : 8, + "line_number" : "5.5.40", + "speaker" : "KING HENRY IV", + "text_entry" : "Myself and you, son Harry, will towards Wales," + }, + "sort" : [ + 3199 + ] + }, + { + "_index" : "shakespeare", + "_id" : "3197", + "_score" : null, + "_source" : { + "type" : "line", + "line_id" : 3198, + "play_name" : "Henry IV", + "speech_number" : 8, + "line_number" : "5.5.39", + "speaker" : "KING HENRY IV", + "text_entry" : "Who, as we hear, are busily in arms:" + }, + "sort" : [ + 3198 + ] + }, + { + "_index" : "shakespeare", + "_id" : "3196", + "_score" : null, + "_source" : { + "type" : "line", + "line_id" : 3197, + "play_name" : "Henry IV", + "speech_number" : 8, + "line_number" : "5.5.38", + "speaker" : "KING HENRY IV", + "text_entry" : "To meet Northumberland and the prelate Scroop," + }, + "sort" : [ + 3197 + ] + }, + { + "_index" : "shakespeare", + "_id" : "3195", + "_score" : null, + "_source" : { + "type" : "line", + "line_id" : 3196, + "play_name" : "Henry IV", + "speech_number" : 8, + "line_number" : "5.5.37", + "speaker" : "KING HENRY IV", + "text_entry" : "Towards York shall bend you with your dearest speed," + }, + "sort" : [ + 3196 + ] + } + ] + } +} +``` + +`sort` 参数是一个数组,因此可以按优先级顺序指定多个字段值。 + +如果有两个字段的 `line_id` 值相同,OpenSearch 会使用第二个排序选项 `speech_number`: + +```json +GET shakespeare/_search +{ + "query": { + "term": { + "play_name": { + "value": "Henry IV" + } + } + }, + "sort": [ + { + "line_id": { + "order": "desc" + } + }, + { + "speech_number": { + "order": "desc" + } + } + ] +} +``` + +可以继续按任意数量的字段值排序,以便让结果完全按照所需的顺序排列。排序依据不一定是数值——也可以按日期或时间戳字段排序: + +```json +"sort": [ + { + "date": { + "order": "desc" + } + } + ] +``` + +经过分析的文本字段不能用于对文档(Document)排序,因为倒排索引中只包含分词后的各个词项,而不包含完整的字符串。因此,例如你不能按 `play_name` 排序。 + +要绕过此限制,可以使用映射为 keyword 类型的文本字段原始版本。在以下示例中,`play_name.keyword` 未经分析,你拥有一份完整的原始版本副本可用于排序: + +```json +GET shakespeare/_search +{ + "query": { + "term": { + "play_name": { + "value": "Henry IV" + } + } + }, + "sort": [ + { + "play_name.keyword": { + "order": "desc" + } + } + ] +} +``` + +结果按 `play_name` 字段的字母顺序排列。 + +将 `sort` 与 [`search_after` 参数](/search-plugins/searching-data/paginate#the-search_after-parameter)结合使用,可以更高效地滚动浏览结果。 +结果从 `search_after` 数组中所指定排序值之后的文档开始。 + +请确保 `search_after` 数组中值的数量与 `sort` 数组中的相同,且顺序一致。 +在本例中,请求的是从 `line_id = 3202` 且 `speech_number = 8` 之后的文档开始的结果: + +```json +GET shakespeare/_search +{ + "query": { + "term": { + "play_name": { + "value": "Henry IV" + } + } + }, + "sort": [ + { + "line_id": { + "order": "desc" + } + }, + { + "speech_number": { + "order": "desc" + } + } + ], + "search_after": [ + "3202", + "8" + ] +} +``` + +## 排序模式 + +排序模式适用于按数组字段或多值字段排序的情况。它指定选择哪个数组值来对文档进行排序。对于包含数字数组的数值字段,可以使用 `avg`、`sum` 或 `median` 模式排序。要按最小值或最大值排序,请使用 `min` 或 `max` 模式,这两种模式同时适用于数值和字符串数据类型(data type)。 + +升序排序时默认模式为 `min`,降序排序时默认模式为 `max`。 + +以下示例演示了如何使用排序模式按数组字段排序。 + +假设有一个存放学生成绩的索引(Index)。向该索引中索引两个文档: + +```json +PUT students/_doc/1 +{ + "name": "John Doe", + "grades": [70, 90] +} + +PUT students/_doc/2 +{ + "name": "Mary Major", + "grades": [80, 100] +} +``` + +使用 `avg` 模式按平均成绩从高到低对所有学生排序: + +``` +GET students/_search +{ + "query" : { + "match_all": {} + }, + "sort" : [ + {"grades" : {"order" : "desc", "mode" : "avg"}} + ] +} +``` + +响应中的学生按 `grades` 降序排列: + +```json +{ + "took" : 1, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 2, + "relation" : "eq" + }, + "max_score" : null, + "hits" : [ + { + "_index" : "students", + "_id" : "2", + "_score" : null, + "_source" : { + "name" : "Mary Major", + "grades" : [ + 80, + 100 + ] + }, + "sort" : [ + 90 + ] + }, + { + "_index" : "students", + "_id" : "1", + "_score" : null, + "_source" : { + "name" : "John Doe", + "grades" : [ + 70, + 90 + ] + }, + "sort" : [ + 80 + ] + } + ] + } +} +``` + +## 对嵌套对象排序 + +对 [nested](/field-types/supported-field-types/nested) 对象排序时,请提供 `path` 参数,指定要排序的字段的路径。 + +例如,在索引 `students` 中,将变量 `first_sem` 映射为 `nested`: + +```json +PUT students +{ + "mappings" : { + "properties": { + "first_sem": { + "type" : "nested" + } + } + } +} +``` + +索引两个包含嵌套字段的文档: + +```json +PUT students/_doc/1 +{ + "name": "John Doe", + "first_sem" : { + "grades": [70, 90] + } +} + +PUT students/_doc/2 +{ + "name": "Mary Major", + "first_sem": { + "grades": [80, 100] + } +} +``` + +按平均成绩排序时,请提供嵌套字段的路径: + +```json +GET students/_search +{ + "query" : { + "match_all": {} + }, + "sort" : [ + {"first_sem.grades": { + "order" : "desc", + "mode" : "avg", + "nested": { + "path": "first_sem" + } + } + } + ] +} +``` + +## 处理缺失值 + +`missing` 参数指定如何处理缺失值。内置的有效值为 `_last`(将缺失该值的文档排在最后)和 `_first`(将缺失该值的文档排在最前)。默认值为 `_last`。也可以指定一个自定义值,作为缺失该值的文档的排序值。 + +例如,可以索引一个包含 `average` 字段的文档,以及另一个不含 `average` 字段的文档: + +```json +PUT students/_doc/1 +{ + "name": "John Doe", + "average": 80 +} + +PUT students/_doc/2 +{ + "name": "Mary Major" +} +``` + +对文档排序,将缺失该字段的文档排在最前: + +```json +GET students/_search +{ + "query": { + "match_all": {} + }, + "sort": [ + { + "average": { + "order": "desc", + "missing": "_first" + } + } + ] +} +``` + +响应将文档 2 列在最前: + +```json +{ + "took" : 1, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 2, + "relation" : "eq" + }, + "max_score" : null, + "hits" : [ + { + "_index" : "students", + "_id" : "2", + "_score" : null, + "_source" : { + "name" : "Mary Major" + }, + "sort" : [ + 9223372036854775807 + ] + }, + { + "_index" : "students", + "_id" : "1", + "_score" : null, + "_source" : { + "name" : "John Doe", + "average" : 80 + }, + "sort" : [ + 80 + ] + } + ] + } +} +``` + +## 忽略未映射的字段 + +如果某个字段未被映射(Mapping),默认情况下按该字段排序的搜索请求会失败。为避免这种情况,可以使用 `unmapped_type` 参数,通知 OpenSearch 忽略该字段。例如,如果将 `unmapped_type` 设置为 `long`,该字段将被视为已映射为 `long` 类型。此外,索引中所有带有 `unmapped_type` 字段的文档都会被视为该字段没有值,因此不会按该字段排序。 + +例如,假设有两个索引。在第一个索引中索引一个包含 `average` 字段的文档: + +```json +PUT students/_doc/1 +{ + "name": "John Doe", + "average": 80 +} +``` + +在第二个索引中索引一个不含 `average` 字段的文档: + +```json +PUT students_no_map/_doc/2 +{ + "name": "Mary Major" +} +``` + +搜索两个索引中的所有文档,并按 `average` 字段排序: + +```json +GET students*/_search +{ + "query": { + "match_all": {} + }, + "sort": [ + { + "average": { + "order": "desc" + } + } + ] +} +``` + +默认情况下,由于 `average` 字段未被映射,第二个索引会产生错误: + +```json +{ + "took" : 3, + "timed_out" : false, + "_shards" : { + "total" : 2, + "successful" : 1, + "skipped" : 0, + "failed" : 1, + "failures" : [ + { + "shard" : 0, + "index" : "students_no_map", + "node" : "cam9NWqVSV-jUIkQ3tRubw", + "reason" : { + "type" : "query_shard_exception", + "reason" : "No mapping found for [average] in order to sort on", + "index" : "students_no_map", + "index_uuid" : "JgfRkypKSUSpyU-ZXr9kKA" + } + } + ] + }, + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : null, + "hits" : [ + { + "_index" : "students", + "_id" : "1", + "_score" : null, + "_source" : { + "name" : "John Doe", + "average" : 80 + }, + "sort" : [ + 80 + ] + } + ] + } +} +``` + +可以指定 `unmapped_type` 参数,以忽略未映射的字段: + +```json +GET students*/_search +{ + "query": { + "match_all": {} + }, + "sort": [ + { + "average": { + "order": "desc", + "unmapped_type": "long" + } + } + ] +} +``` + +响应包含两个文档: + +```json +{ + "took" : 4, + "timed_out" : false, + "_shards" : { + "total" : 2, + "successful" : 2, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 2, + "relation" : "eq" + }, + "max_score" : null, + "hits" : [ + { + "_index" : "students", + "_id" : "1", + "_score" : null, + "_source" : { + "name" : "John Doe", + "average" : 80 + }, + "sort" : [ + 80 + ] + }, + { + "_index" : "students_no_map", + "_id" : "2", + "_score" : null, + "_source" : { + "name" : "Mary Major" + }, + "sort" : [ + -9223372036854775808 + ] + } + ] + } +} +``` + +## 跟踪评分 + +默认情况下,按字段排序时不会计算评分。可以将 `track_scores` 设置为 `true` 来计算和跟踪评分: + +```json +GET students/_search +{ + "query": { + "match_all": {} + }, + "sort": [ + { + "average": { + "order": "desc" + } + } + ], + "track_scores": true +} +``` + +## 按地理距离排序 + +可以按 `_geo_distance` 对文档排序。支持以下参数。 + +参数 | 说明 +:--- | :--- +distance_type | 指定计算距离的方法。有效值为 `arc` 和 `plane`。`plane` 方法速度更快,但在长距离或靠近两极时精度较低。默认值为 `arc`。 +mode | 指定如何处理包含多个地理点(geopoint)的字段。默认情况下,升序排序时文档按最短距离排序,降序排序时按最长距离排序。有效值为 `min`、`max`、`median` 和 `avg`。 +unit | 指定计算排序值时使用的单位。默认值为米(`m`)。 +ignore_unmapped | 指定如何处理未映射的字段。将 `ignore_unmapped` 设置为 `true` 可忽略未映射的字段。默认值为 `false`(遇到未映射的字段时报错)。 + +::: info 注意 +`_geo_distance` 参数不支持 `missing_values`。当文档不包含用于计算距离的字段时,距离始终被视为 `infinity`。 +::: + +例如,索引两个包含地理点的文档: + +```json +PUT testindex1/_doc/1 +{ + "point": [74.00, 40.71] +} + +PUT testindex1/_doc/2 +{ + "point": [73.77, -69.63] +} +``` + +搜索所有文档,并按与所提供的点之间的距离对其排序: + +```json +GET testindex1/_search +{ + "sort": [ + { + "_geo_distance": { + "point": [59, -54], + "order": "asc", + "unit": "km", + "distance_type": "arc", + "mode": "min", + "ignore_unmapped": true + } + } + ], + "query": { + "match_all": {} + } +} +``` + +响应包含排序后的文档: + +```json +{ + "took" : 864, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 2, + "relation" : "eq" + }, + "max_score" : null, + "hits" : [ + { + "_index" : "testindex1", + "_id" : "2", + "_score" : null, + "_source" : { + "point" : [ + 73.77, + -69.63 + ] + }, + "sort" : [ + 1891.2667493895767 + ] + }, + { + "_index" : "testindex1", + "_id" : "1", + "_score" : null, + "_source" : { + "point" : [ + 74.0, + 40.71 + ] + }, + "sort" : [ + 10628.402240213345 + ] + } + ] + } +} +``` + +::: info 注意 +可以使用地理点字段类型(field type)支持的任意格式提供坐标。有关所有格式的说明,请参阅[地理点字段类型文档](/field-types/supported-field-types/geo-point)。 +::: + +要向 `_geo_distance` 传入多个地理点,请使用数组: + +```json +GET testindex1/_search +{ + "sort": [ + { + "_geo_distance": { + "point": [[59, -54], [60, -53]], + "order": "asc", + "unit": "km", + "distance_type": "arc", + "mode": "min", + "ignore_unmapped": true + } + } + ], + "query": { + "match_all": {} + } +} +``` + +对于每个文档,排序距离按照 `mode` 的指定,取搜索中提供的所有点到文档中所有点之间距离的最小值、最大值或平均值。 + +## 性能考虑 + +用于排序的字段值会被加载到内存中。因此,为了将开销降到最低,建议将[数值类型](/field-types/supported-field-types/numeric)映射为可接受的最小类型,例如 `short`、`integer` 和 `float`。[字符串类型](/field-types/supported-field-types/string)的排序字段不应经过分析或分词。 diff --git a/i18n/zh/search-plugins/semantic-search.md b/i18n/zh/search-plugins/semantic-search.md new file mode 100644 index 00000000..a9e29802 --- /dev/null +++ b/i18n/zh/search-plugins/semantic-search.md @@ -0,0 +1,286 @@ +--- +title: 语义搜索 +--- + +# 语义搜索 + +语义搜索(semantic search)会考虑查询(Query)的上下文和意图。在 OpenSearch 中,语义搜索通过神经搜索(Neural Search)结合文本嵌入模型(model)来实现。语义搜索会创建一个稠密向量(dense vector,即一个浮点数列表),并将数据摄取到 k-NN 索引(Index)中。 + +::: info 注意 +**前提条件**
+在使用语义搜索之前,必须先设置一个文本嵌入模型。有关更多信息,请参阅[选择模型](/ml-commons-plugin/integrating-ml-models#choosing-a-model)。 +::: + +## 使用语义搜索 + +要使用语义搜索,请按照以下步骤操作: + +1. [创建摄取管道](#step-1-create-an-ingest-pipeline)。 +1. [创建用于摄取的索引](#step-2-create-an-index-for-ingestion)。 +1. [将文档摄取到索引中](#step-3-ingest-documents-into-the-index)。 +1. [使用神经搜索搜索索引](#step-4-search-the-index-using-neural-search)。 + +## 第 1 步:创建摄取管道 + +要生成向量嵌入(embedding),需要创建一个[摄取管道(Ingest Pipeline)](/api-reference/ingest-apis/),其中包含一个 [`text_embedding` 处理器](/ingest-pipelines/processors/text-embedding),用于将文档(Document)字段中的文本转换为向量嵌入。处理器的 `field_map` 决定了从哪些输入字段(Field)生成向量嵌入,以及将嵌入存储到哪些输出字段中。 + +以下示例请求创建了一个摄取管道,其中 `passage_text` 中的文本将被转换为文本嵌入,嵌入将存储在 `passage_embedding` 中: + +```json +PUT /_ingest/pipeline/nlp-ingest-pipeline +{ + "description": "A text embedding pipeline", + "processors": [ + { + "text_embedding": { + "model_id": "bQ1J8ooBpBj3wT4HVUsb", + "field_map": { + "passage_text": "passage_embedding" + } + } + } + ] +} +``` + +## 第 2 步:创建用于摄取的索引 + +为了使用管道中定义的文本嵌入处理器,需要创建一个 k-NN 索引,并将上一步创建的管道添加为默认管道。请确保 `field_map` 中定义的字段被映射(Mapping)为正确的类型。继续以本示例为例,`passage_embedding` 字段必须映射为 k-NN 向量,且其维度与模型维度相匹配。同样,`passage_text` 字段应映射为 `text`。 + +以下示例请求创建了一个设置了默认摄取管道的 k-NN 索引: + +```json +PUT /my-nlp-index +{ + "settings": { + "index.knn": true, + "default_pipeline": "nlp-ingest-pipeline" + }, + "mappings": { + "properties": { + "id": { + "type": "text" + }, + "passage_embedding": { + "type": "knn_vector", + "dimension": 768, + "method": { + "engine": "lucene", + "space_type": "l2", + "name": "hnsw", + "parameters": {} + } + }, + "passage_text": { + "type": "text" + } + } + } +} +``` + +有关创建 k-NN 索引及其支持的方法的更多信息,请参阅 [k-NN 索引](/search-plugins/knn/knn-index)。 + +## 第 3 步:将文档摄取到索引中 + +要将文档摄取到上一步创建的索引中,请发送以下请求: + +```json +PUT /my-nlp-index/_doc/1 +{ + "passage_text": "Hello world", + "id": "s1" +} +``` + +```json +PUT /my-nlp-index/_doc/2 +{ + "passage_text": "Hi planet", + "id": "s2" +} +``` + +在文档被摄取到索引之前,摄取管道会对文档运行 `text_embedding` 处理器,为 `passage_text` 字段生成文本嵌入。被索引的文档包含存放原始文本的 `passage_text` 字段,以及存放向量嵌入的 `passage_embedding` 字段。 + +## 第 4 步:使用神经搜索搜索索引 + +要在索引上执行向量搜索,可以在 [k-NN 插件 API](/search-plugins/knn/api#search-model) 或 [Query DSL](/query-dsl/) 查询中使用 `neural` 查询子句。可以使用 [k-NN 搜索过滤器](/search-plugins/knn/filter-search-knn)对结果进行细化。 + +以下示例请求使用 Boolean 查询组合了一个过滤子句和两个查询子句——一个 neural 查询和一个 `match` 查询。`script_score` 查询为各查询子句分配自定义权重: + +```json +GET /my-nlp-index/_search +{ + "_source": { + "excludes": [ + "passage_embedding" + ] + }, + "query": { + "bool": { + "filter": { + "wildcard": { "id": "*1" } + }, + "should": [ + { + "script_score": { + "query": { + "neural": { + "passage_embedding": { + "query_text": "Hi world", + "model_id": "bQ1J8ooBpBj3wT4HVUsb", + "k": 100 + } + } + }, + "script": { + "source": "_score * 1.5" + } + } + }, + { + "script_score": { + "query": { + "match": { + "passage_text": "Hi world" + } + }, + "script": { + "source": "_score * 1.7" + } + } + } + ] + } + } +} +``` + +响应包含匹配的文档: + +```json +{ + "took" : 36, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 1.2251667, + "hits" : [ + { + "_index" : "my-nlp-index", + "_id" : "1", + "_score" : 1.2251667, + "_source" : { + "passage_text" : "Hello world", + "id" : "s1" + } + } + ] + } +} +``` + +## 在索引或字段上设置默认模型 + +[`neural`](/query-dsl/specialized/neural) 查询需要一个模型 ID 来生成向量嵌入。为了避免在每个 neural 查询请求中都传入模型 ID,可以在 k-NN 索引或字段上设置默认模型。 + +首先,创建一个带有 [`neural_query_enricher`](/search-plugins/search-pipelines/neural-query-enricher) 请求处理器的[搜索管道(Search Pipeline)](/search-plugins/search-pipelines/)。要为索引设置默认模型,请在 `default_model_id` 参数中提供模型 ID。要为特定字段设置默认模型,请在 `neural_field_default_id` 映射中提供字段名及对应的模型 ID。如果同时提供了 `default_model_id` 和 `neural_field_default_id`,则 `neural_field_default_id` 优先: + +```json +PUT /_search/pipeline/default_model_pipeline +{ + "request_processors": [ + { + "neural_query_enricher" : { + "default_model_id": "bQ1J8ooBpBj3wT4HVUsb", + "neural_field_default_id": { + "my_field_1": "uZj0qYoBMtvQlfhaYeud", + "my_field_2": "upj0qYoBMtvQlfhaZOuM" + } + } + } + ] +} +``` + +然后为索引设置默认模型: + +```json +PUT /my-nlp-index/_settings +{ + "index.search.default_pipeline" : "default_model_pipeline" +} +``` + +现在,搜索时可以省略模型 ID: + +```json +GET /my-nlp-index/_search +{ + "_source": { + "excludes": [ + "passage_embedding" + ] + }, + "query": { + "neural": { + "passage_embedding": { + "query_text": "Hi world", + "k": 100 + } + } + } +} +``` + +响应包含两个文档: + +```json +{ + "took" : 41, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 2, + "relation" : "eq" + }, + "max_score" : 1.22762, + "hits" : [ + { + "_index" : "my-nlp-index", + "_id" : "2", + "_score" : 1.22762, + "_source" : { + "passage_text" : "Hi planet", + "id" : "s2" + } + }, + { + "_index" : "my-nlp-index", + "_id" : "1", + "_score" : 1.2251667, + "_source" : { + "passage_text" : "Hello world", + "id" : "s1" + } + } + ] + } +} +``` diff --git a/i18n/zh/search-plugins/sql/cli.md b/i18n/zh/search-plugins/sql/cli.md new file mode 100644 index 00000000..cad81a34 --- /dev/null +++ b/i18n/zh/search-plugins/sql/cli.md @@ -0,0 +1,109 @@ +--- +title: SQL 和 PPL CLI +--- + +# SQL 和 PPL CLI + +SQL 和 PPL 命令行界面(CLI)是一个独立的 Python 应用程序,可以通过 `opensearchsql` 命令启动。 + + 要使用 SQL 和 PPL CLI,请在 OpenSearch 实例上安装 SQL 插件(plugin),在 MacOS 或 Linux 上运行 CLI,并连接到任意有效的 OpenSearch 端点。 + +![SQL CLI](/images/cli.gif) + +## 功能 + +SQL 和 PPL CLI 具有以下功能: + +- 多行输入 +- 支持 PPL +- SQL 语法和索引名称的自动补全(autocomplete) +- 语法高亮 +- 格式化输出: + - 表格格式 + - 字段名称带颜色显示 + - 默认启用水平显示;当输出对终端来说过宽时使用垂直显示,以获得更好的可视化效果 + - 对大量输出进行分页 +- 无论是否启用安全功能均可使用 +- 支持加载配置文件 +- 支持所有 SQL 插件查询 + +## 安装 + +启动本地 OpenSearch 实例,并确保已安装 SQL 插件。 + +1. 安装 CLI: +```console +pip3 install opensearchsql +``` + +::: info 注意 +SQL CLI 仅适用于 Python 3。 +::: + +2. 运行以下命令启动 CLI: +```console +opensearchsql https://localhost:9200 --username admin --password admin +``` +默认情况下,`opensearchsql` 命令连接到 http://localhost:9200。 + +## 配置 + +首次启动 SQL CLI 时,会自动在 `~/.config/opensearchsql-cli/config`(MacOS 和 Linux)创建配置文件,此后会自动加载该配置。 + +你可以配置以下连接属性: + +- `endpoint`:无需指定选项。启动命令 `opensearchsql` 之后的任何内容都会被视为端点。如果未提供端点,SQL CLI 默认连接到 http://localhost:9200。 +- `-u/-w`:支持用于 HTTP 基本身份验证的用户名和密码,例如配合 Security 插件或 Amazon OpenSearch Service 的细粒度访问控制使用。 +- `--aws-auth`:启用 AWS sigV4 身份验证以连接到 Amazon OpenSearch 端点。与 AWS CLI(`aws configure`)配合使用,读取本地 AWS 配置进行身份验证和连接。 + +有关所有可用配置的列表,请参阅 [clirc](https://github.com/opensearch-project/sql/blob/1.x/sql-cli/src/opensearch_sql_cli/conf/clirc)。 + +## 使用 CLI + +1. 运行 CLI 工具。如果集群使用默认安全设置运行,请使用以下命令: +```console +opensearchsql --username admin --password admin https://localhost:9200 +``` +如果集群未启用安全功能,请运行: +```console +opensearchsql +``` + +2. 运行一条示例 SQL 命令: +```sql +SELECT * FROM accounts; +``` + +默认情况下,最多显示 200 行输出。如需显示更多结果,请添加带有所需值的 `LIMIT` 子句。 + +::: tip 提示 +要退出 CLI 工具,请按 **Ctrl+D**。 +::: + +## 在 CLI 中使用 PPL + +1. 运行 CLI 时指定查询语言: +```console +opensearchsql -l ppl +``` + +2. 执行 PPL 查询: +```sql +source=accounts | fields firstname, lastname +``` + +## 查询选项 + +使用以下命令行选项运行单个查询: + +- `-q`:后跟单个查询 +- `-f`:指定 JDBC 或原始格式输出 +- `-v`:垂直显示数据 +- `-e`:将 SQL 转换为 DSL + +## CLI 选项 + +- `--help`:选项帮助页面 +- `-l`:查询语言选项。可用选项为 `sql` 和 `ppl`。默认值为 `sql` +- `-p`:始终使用分页器显示输出 +- `--clirc`:提供配置文件的路径 diff --git a/i18n/zh/search-plugins/sql/datatypes.md b/i18n/zh/search-plugins/sql/datatypes.md new file mode 100644 index 00000000..c8e56113 --- /dev/null +++ b/i18n/zh/search-plugins/sql/datatypes.md @@ -0,0 +1,112 @@ +--- +title: 数据类型 +--- + +# 数据类型 + +下表列出了 SQL 插件(plugin)支持的数据类型(data type),以及每种类型与 SQL 和 OpenSearch 数据类型之间的映射关系: + +| OpenSearch SQL 类型 | OpenSearch 类型 | SQL 类型 +:--- | :--- | :--- +boolean | boolean | BOOLEAN +byte | byte | TINYINT +short | byte | SMALLINT +integer | integer | INTEGER +long | long | BIGINT +float | float | REAL +half_float | float | FLOAT +scaled_float | float | DOUBLE +double | double | DOUBLE +keyword | string | VARCHAR +text | text | VARCHAR +date | timestamp | TIMESTAMP +date_nanos | timestamp | TIMESTAMP +ip | ip | VARCHAR +date | timestamp | TIMESTAMP +binary | binary | VARBINARY +object | struct | STRUCT +nested | array | STRUCT + +除上述类型外,SQL 插件还支持 `datetime` 类型,但它在 OpenSearch 和 SQL 中都没有对应的映射。 +要使用没有对应映射的函数,必须将数据类型显式转换为有对应映射的类型。 + +## 日期和时间类型 + +日期和时间类型表示一个时间段:`DATE`、`TIME`、`DATETIME`、`TIMESTAMP` 和 `INTERVAL`。默认情况下,OpenSearch DSL 只使用 `date` 类型作为与日期时间相关的类型,它包含绝对时间点的全部信息。 + +为了与 SQL 集成,除 `timestamp` 类型外,其他每种类型都只保存时间段信息的一部分。关于日期时间函数的用法,请参阅 [datetime](/search-plugins/sql/functions#date-and-time)。某些函数可能会对输入参数的类型有所限制。 + +### Date + +`date` 类型表示与时区无关的日历日期。一个给定的日期值是一个 24 小时的时间段,但该时间段在不同时区有所不同,并且在夏令时期间可能会有小时数的变化。`date` 类型不包含时间信息,仅支持 `1000-01-01` 到 `9999-12-31` 的范围。 + +| 类型 | 语法 | 范围 +:--- | :--- | :--- +date | `yyyy-MM-dd` | `0001-01-01` 到 `9999-12-31` + +### Time + +`time` 类型表示与时区无关的时钟时间。`time` 类型不包含日期信息。 + +| 类型 | 语法 | 范围 +:--- | :--- | :--- +time | `hh:mm:ss[.fraction]` | `00:00:00.0000000000` 到 `23:59:59.9999999999` + +### Datetime + +`datetime` 类型是日期和时间的组合,不包含时区信息。关于包含日期、时间和时区信息的绝对时间点,请参阅 [Timestamp](#timestamp)。 + +| 类型 | 语法 | 范围 +:--- | :--- | :--- +datetime | `yyyy-MM-dd hh:mm:ss[.fraction]` | `0001-01-01 00:00:00.0000000000` 到 `9999-12-31 23:59:59.9999999999` + +### Timestamp + +`timestamp` 类型是一个与时区或惯例无关的绝对时刻。例如,对于某个给定的时间点,如果将时间戳更改为另一个时区,其值也会相应地变化。 + +`timestamp` 类型的存储方式与其他类型不同。存储时它会从当前时区转换为 UTC,检索时再从 UTC 转换回所设置的时区。 + +| 类型 | 语法 | 范围 +:--- | :--- | :--- +timestamp | `yyyy-MM-dd hh:mm:ss[.fraction]` | `0001-01-01 00:00:01.9999999999` UTC 到 `9999-12-31 23:59:59.9999999999` + +### Interval + +`interval` 类型表示一段时间长度或一个时间周期。 + +| 类型 | 语法 +:--- | :--- +interval | `INTERVAL expr unit` + +`expr` 是任意最终能计算出数量值的表达式。unit 表示用于解释该数量的单位,包括 `MICROSECOND`、`SECOND`、`MINUTE`、`HOUR`、`DAY`、`WEEK`、`MONTH`、`QUARTER` 和 `YEAR`。`INTERVAL` 关键字和单位说明符不区分大小写。 + +`interval` 类型有两类时间间隔:年-周间隔和日-时间隔。 + +- 年-周间隔存储年、季度、月和周。 +- 日-时间隔存储天、小时、分钟、秒和微秒。 + +### 日期和时间类型之间的转换 + +除 `interval` 类型外,所有日期和时间类型之间都可以相互转换。转换可能会改变值或导致部分信息丢失,例如从 `datetime` 值中提取 `time` 值,或将 `date` 值转换为 `datetime` 值等。 + +SQL 插件对各类型支持以下转换规则: + +**从 date 转换** + +- 由于 `date` 值不含任何时间信息,将其转换为 `time` 类型没有意义,结果始终为零时间值 `00:00:00`。 +- 由于缺少时间信息,从 `date` 转换为 `datetime` 时会进行数据填充。默认情况下,会在原日期后附加时间 `00:00:00`,构成一个 `datetime` 实例。例如,将 `2020-08-17` 转换为 `datetime` 类型的结果是 `2020-08-17 00:00:00`。 +- 转换为 `timestamp` 类型时,会同时补充 `time` 值和 `timezone` 信息:在日期后附加零时间值 `00:00:00` 和会话时区(默认为 UTC)。例如,在会话时区为 UTC 时,将 `2020-08-17` 转换为 `datetime` 类型的结果是 `2020-08-17 00:00:00 UTC`。 + +**从 time 转换** + +- 由于 `time` 类型不包含任何日期信息,因此无法将其转换为其他任何日期和时间类型。 + +**从 datetime 转换** + +- 将 `datetime` 转换为 `date` 会从 `datetime` 值中提取日期值。例如,将 `2020-08-17 14:09:00` 转换为 `date` 类型的结果是 `2020-08-08`。 +- 将 `datetime` 转换为 `time` 会从 `datetime` 值中提取时间值。例如,将 `2020-08-17 14:09:00` 转换为 `time` 类型的结果是 `14:09:00`。 +- 由于 `datetime` 类型不包含时区信息,转换为 `timestamp` 类型时会用会话时区填充时区值。例如,将 `2020-08-17 14:09:00`(UTC)转换为 `timestamp` 类型的结果是 `2020-08-17 14:09:00 UTC`。 + +**从 timestamp 转换** + +- 从 `timestamp` 类型转换为 `date` 类型会提取日期值,转换为 `time` 类型会提取时间值。从 `timestamp` 类型转换为 `datetime` 类型只会提取 `datetime` 值,并舍弃时区值。例如,将 `2020-08-17 14:09:00` UTC 转换为 `date` 类型的结果是 `2020-08-17`,转换为 `time` 类型的结果是 `14:09:00`,转换为 `datetime` 类型的结果是 `2020-08-17 14:09:00`。 diff --git a/i18n/zh/search-plugins/sql/full-text.md b/i18n/zh/search-plugins/sql/full-text.md new file mode 100644 index 00000000..1fa7f935 --- /dev/null +++ b/i18n/zh/search-plugins/sql/full-text.md @@ -0,0 +1,485 @@ +--- +title: 全文搜索 +--- + +# 全文搜索 + +使用 SQL 命令进行全文搜索。SQL 插件(plugin)支持 OpenSearch 中可用的全文查询(full-text query)的一个子集。 + +要了解 OpenSearch 中的全文查询,请参阅[全文查询](/query-dsl/full-text/)。 + +## Match + +使用 `MATCH` 函数(function)搜索在指定字段(Field)中与 `string`、`number`、`date` 或 `boolean` 值匹配的文档(Document)。 + +### 语法 + +```sql +match(field_expression, query_expression[, option=]*) +``` + +可以按任意顺序指定以下选项: + +- `analyzer` +- `auto_generate_synonyms_phrase` +- `fuzziness` +- `max_expansions` +- `prefix_length` +- `fuzzy_transpositions` +- `fuzzy_rewrite` +- `lenient` +- `operator` +- `minimum_should_match` +- `zero_terms_query` +- `boost` + +有关参数说明和支持的值,请参阅 `match` 查询[文档](/query-dsl/full-text/match)。 + +### 示例 1:在 `message` 字段中搜索文本 "this is a test": + +```json +GET my_index/_search +{ + "query": { + "match": { + "message": "this is a test" + } + } +} +``` + +*SQL 查询:* +```sql +SELECT message FROM my_index WHERE match(message, "this is a test") +``` +*PPL 查询:* +```ppl +SOURCE=my_index | WHERE match(message, "this is a test") | FIELDS message +``` + +### 示例 2:使用 `operator` 参数搜索 `message` 字段: + +```json +GET my_index/_search +{ + "query": { + "match": { + "message": { + "query": "this is a test", + "operator": "and" + } + } + } +} +``` + +*SQL 查询:* +```sql +SELECT message FROM my_index WHERE match(message, "this is a test", operator='and') +``` +*PPL 查询:* +```ppl +SOURCE=my_index | WHERE match(message, "this is a test", operator='and') | FIELDS message +``` + +### 示例 3:使用 `operator` 和 `zero_terms_query` 参数搜索 `message` 字段: + +```json +GET my_index/_search +{ + "query": { + "match": { + "message": { + "query": "to be or not to be", + "operator": "and", + "zero_terms_query": "all" + } + } + } +} +``` + +*SQL 查询:* +```sql +SELECT message FROM my_index WHERE match(message, "this is a test", operator='and', zero_terms_query='all') +``` +*PPL 查询:* +```sql +SOURCE=my_index | WHERE match(message, "this is a test", operator='and', zero_terms_query='all') | FIELDS message +``` + +## Multi-match + +要在多个字段中搜索文本,请使用 `MULTI_MATCH` 函数。该函数对应于搜索引擎中使用的 `multi_match` 查询,返回在一个或多个指定字段中与所提供的文本、数字、日期或布尔值匹配的文档。 + +### 语法 {#syntax-1} + +`MULTI_MATCH` 函数使用 **^** 字符对特定字段进行*权重提升*(boost)。权重提升是一种乘数,使某个字段中的匹配比其他字段中的匹配具有更高的权重。语法支持使用双引号、单引号、反引号或不加任何引号来指定字段。使用星号 ``"*"`` 搜索所有字段。星号必须加引号。 + +```sql +multi_match([field_expression+], query_expression[, option=]*) +``` + +权重是可选的,在字段名之后指定。它可以用 `caret` 字符 `^` 或空白字符分隔。请参考以下示例: + +```sql +multi_match(["Tags" ^ 2, 'Title' 3.4, `Body`, Comments ^ 0.3], ...) +multi_match(["*"], ...) +``` + +可以按任意顺序为 `MULTI_MATCH` 指定以下选项: + +- `analyzer` +- `auto_generate_synonyms_phrase` +- `cutoff_frequency` +- `fuzziness` +- `fuzzy_transpositions` +- `lenient` +- `max_expansions` +- `minimum_should_match` +- `operator` +- `prefix_length` +- `tie_breaker` +- `type` +- `slop` +- `zero_terms_query` +- `boost` + +有关参数说明和支持的值,请参阅 `multi_match` 查询[文档](/query-dsl/full-text/multi-match)。 + +### 例如,通过 REST API 在 `firstname` 或 `lastname` 字段中搜索 `Dale`: + +```json +GET accounts/_search +{ + "query": { + "multi_match": { + "query": "Lane Street", + "fields": [ "address" ], + } + } +} +``` +可以在 *SQL* 中使用 `multi_match` 函数调用 +```sql +SELECT firstname, lastname +FROM accounts +WHERE multi_match(['*name'], 'Dale') +``` +或使用 `multi_match` *PPL* 函数调用 +```sql +SOURCE=accounts | WHERE multi_match(['*name'], 'Dale') | fields firstname, lastname +``` + +| firstname | lastname +:--- | :--- +Dale | Adams + +## Query string + +要根据运算符拆分文本,请使用 `QUERY_STRING` 函数。`QUERY_STRING` 函数支持逻辑连接词、通配符、正则表达式和邻近搜索。 +该函数对应于搜索引擎中使用的 `query_string` 查询,返回在一个或多个指定字段中与所提供的文本、数字、日期或布尔值匹配的文档。 + +### 语法 {#syntax-2} + +`QUERY_STRING` 函数的语法与 `MATCH_QUERY` 类似,并使用 **^** 字符对特定字段进行*权重提升*。权重提升是一种乘数,使某个字段中的匹配比其他字段中的匹配具有更高的权重。语法支持使用双引号、单引号、反引号或不加任何引号来指定字段。使用星号 ``"*"`` 搜索所有字段。星号必须加引号。 + +```sql +query_string([field_expression+], query_expression[, option=]*) +``` + +权重是可选的,在字段名之后指定。它可以用 `caret` 字符 `^` 或空白字符分隔。请参考以下示例: + +```sql +query_string(["Tags" ^ 2, 'Title' 3.4, `Body`, Comments ^ 0.3], ...) +query_string(["*"], ...) +``` + +可以按任意顺序为 `QUERY_STRING` 指定以下选项: + +- `analyzer` +- `allow_leading_wildcard` +- `analyze_wildcard` +- `auto_generate_synonyms_phrase_query` +- `boost` +- `default_operator` +- `enable_position_increments` +- `fuzziness` +- `fuzzy_rewrite` +- `escape` +- `fuzzy_max_expansions` +- `fuzzy_prefix_length` +- `fuzzy_transpositions` +- `lenient` +- `max_determinized_states` +- `minimum_should_match` +- `quote_analyzer` +- `phrase_slop` +- `quote_field_suffix` +- `rewrite` +- `type` +- `tie_breaker` +- `time_zone` + +有关参数说明和支持的值,请参阅 `query_string` 查询[文档](/query-dsl/full-text/query-string)。 + +### 在 SQL 和 PPL 查询中使用 `query_string` 的示例: {#example-of-using-querystring-in-sql-and-ppl-queries} + +以下 REST API 搜索请求 + +```json +GET accounts/_search +{ + "query": { + "query_string": { + "query": "Lane Street", + "fields": [ "address" ], + } + } +} +``` + +可以在 *SQL* 中调用 + +```sql +SELECT account_number, address +FROM accounts +WHERE query_string(['address'], 'Lane Street', default_operator='OR') +``` + +或在 *PPL* 中调用 + +```sql +SOURCE=accounts | WHERE query_string(['address'], 'Lane Street', default_operator='OR') | fields account_number, address +``` + +| account_number | address +:--- | :--- +1 | 880 Holmes Lane +6 | 671 Bristol Street +13 | 789 Madison Street + +## Match phrase + +要搜索精确短语,请使用 `MATCHPHRASE` 或 `MATCH_PHRASE` 函数。 + +### 语法 {#syntax-3} + +```sql +matchphrasequery(field_expression, query_expression) +matchphrase(field_expression, query_expression[, option=]*) +match_phrase(field_expression, query_expression[, option=]*) +``` + +`MATCHPHRASE`/`MATCH_PHRASE` 函数允许按任意顺序指定以下选项: + +- `analyzer` +- `slop` +- `zero_terms_query` +- `boost` + +有关参数说明和支持的值,请参阅 `match_phrase` 查询[文档](/query-dsl/full-text/match-phrase)。 + +### 在 SQL 和 PPL 查询中使用 `match_phrase` 的示例: {#example-of-using-matchphrase-in-sql-and-ppl-queries} + +以下 REST API 搜索请求 +```json +GET accounts/_search +{ + "query": { + "match_phrase": { + "address": { + "query": "880 Holmes Lane" + } + } + } +} +``` +可以在 *SQL* 中调用 +```sql +SELECT account_number, address +FROM accounts +WHERE match_phrase(address, '880 Holmes Lane') +``` +或在 *PPL* 中调用 +```sql +SOURCE=accounts | WHERE match_phrase(address, '880 Holmes Lane') | FIELDS account_number, address +``` + +| account_number | address +:--- | :--- +1 | 880 Holmes Lane + +## Simple query string + +`simple_query_string` 函数对应于 OpenSearch 中的 `simple_query_string` 查询。它返回在一个或多个指定字段中与所提供的文本、数字、日期或布尔值匹配的文档。 +使用 **^** 可以对特定字段进行*权重提升*。权重提升是一种乘数,使某个字段中的匹配比其他字段中的匹配具有更高的权重。 + +### 语法 {#syntax-4} + +语法支持使用双引号、单引号、反引号或不加任何引号来指定字段。使用星号 ``"*"`` 搜索所有字段。星号必须加引号。 + +```sql +simple_query_string([field_expression+], query_expression[, option=]*) +``` + +权重是可选的,在字段名之后指定。它可以用 `caret` 字符 `^` 或空白字符分隔。请参考以下示例: + +```sql +simple_query_string(["Tags" ^ 2, 'Title' 3.4, `Body`, Comments ^ 0.3], ...) +simple_query_string(["*"], ...) +``` + +可以按任意顺序为 `SIMPLE_QUERY_STRING` 指定以下选项: + +- `analyze_wildcard` +- `analyzer` +- `auto_generate_synonyms_phrase_query` +- `boost` +- `default_operator` +- `flags` +- `fuzzy_max_expansions` +- `fuzzy_prefix_length` +- `fuzzy_transpositions` +- `lenient` +- `minimum_should_match` +- `quote_field_suffix` + +有关参数说明和支持的值,请参阅 `simple_query_string` 查询[文档](/query-dsl/full-text/simple-query-string)。 + +### 在 SQL 和 PPL 查询中使用 `simple_query_string` 的*示例*: + +以下 REST API 搜索请求 +```json +GET accounts/_search +{ + "query": { + "simple_query_string": { + "query": "Lane Street", + "fields": [ "address" ], + } + } +} +``` +可以在 *SQL* 中调用 +```sql +SELECT account_number, address +FROM accounts +WHERE simple_query_string(['address'], 'Lane Street', default_operator='OR') +``` +或在 *PPL* 中调用 +```sql +SOURCE=accounts | WHERE simple_query_string(['address'], 'Lane Street', default_operator='OR') | fields account_number, address +``` + +| account_number | address +:--- | :--- +1 | 880 Holmes Lane +6 | 671 Bristol Street +13 | 789 Madison Street + +## Match phrase prefix + +要按给定前缀搜索短语,请使用 `MATCH_PHRASE_PREFIX` 函数,它会将查询字符串中的最后一个词项构造为前缀查询。 + +### 语法 {#syntax-5} + +```sql +match_phrase_prefix(field_expression, query_expression[, option=]*) +``` + +`MATCH_PHRASE_PREFIX` 函数允许按任意顺序指定以下选项: + +- `analyzer` +- `slop` +- `max_expansions` +- `zero_terms_query` +- `boost` + +有关参数说明和支持的值,请参阅 `match_phrase_prefix` 查询[文档](/query-dsl/full-text/match-phrase-prefix)。 + +### 在 SQL 和 PPL 查询中使用 `match_phrase_prefix` 的*示例*: + +以下 REST API 搜索请求 +```json +GET accounts/_search +{ + "query": { + "match_phrase_prefix": { + "author": { + "query": "Alexander Mil" + } + } + } +} +``` +可以在 *SQL* 中调用 +```sql +SELECT author, title +FROM books +WHERE match_phrase_prefix(author, 'Alexander Mil') +``` +或在 *PPL* 中调用 +```sql +source=books | where match_phrase_prefix(author, 'Alexander Mil') | fields author, title +``` + +| author | title +:--- | :--- +Alan Alexander Milne | The House at Pooh Corner +Alan Alexander Milne | Winnie-the-Pooh + +## Match boolean prefix + +使用 `match_bool_prefix` 函数搜索仅在指定字段前缀上与文本匹配的文档。 + +### 语法 {#syntax-6} + +```sql +match_bool_prefix(field_expression, query_expression[, option=]*) +``` + +`MATCH_BOOL_PREFIX` 函数允许按任意顺序指定以下选项: + +- `minimum_should_match` +- `fuzziness` +- `prefix_length` +- `max_expansions` +- `fuzzy_transpositions` +- `fuzzy_rewrite` +- `boost` +- `analyzer` +- `operator` + +有关参数说明和支持的值,请参阅 `match_bool_prefix` 查询[文档](/query-dsl/full-text/match-bool-prefix)。 + +### 在 SQL 和 PPL 查询中使用 `match_bool_prefix` 的示例: + +以下 REST API 搜索请求 +```json +GET accounts/_search +{ + "query": { + "match_bool_prefix": { + "address": { + "query": "Bristol Stre" + } + } + } +} +``` +可以在 *SQL* 中调用 +```sql +SELECT firstname, address +FROM accounts +WHERE match_bool_prefix(address, 'Bristol Stre') +``` +或在 *PPL* 中调用 +```sql +source=accounts | where match_bool_prefix(address, 'Bristol Stre') | fields firstname, address +``` + +| firstname | address +:--- | :--- +Hattie | 671 Bristol Street +Nanette | 789 Madison Street diff --git a/i18n/zh/search-plugins/sql/functions.md b/i18n/zh/search-plugins/sql/functions.md new file mode 100644 index 00000000..35081cf5 --- /dev/null +++ b/i18n/zh/search-plugins/sql/functions.md @@ -0,0 +1,183 @@ +--- +title: 函数 +--- + +# 函数 + +要让大多数字符串函数(function)正常工作,必须在文档映射(Mapping)中启用 fielddata。 + +规范中以泛型类型 `T` 作为参数,展示函数的返回类型。 +例如,`abs(number T) -> T` 表示函数 `abs` 接受一个类型为 `T` 的数值参数,`T` 可以是 `number` 类型的任意子类型,并且返回值的类型就是 `T` 的实际类型。 + +SQL 插件(plugin)支持以下 SQL 和 PPL 语言通用的常用函数。 + +## 数学函数 + +| 函数 | 规范 | 示例 | +|:-----------|:-----------------------------------------------------------------|:-----------------------------------------------| +| `abs` | `abs(number T) -> T` | `SELECT abs(0.5)` | +| `add` | `add(number T, number T) -> T` | `SELECT add(1, 5)` | +| `cbrt` | `cbrt(number T) -> double` | `SELECT cbrt(8)` | +| `ceil` | `ceil(number T) -> T` | `SELECT ceil(0.5)` | +| `conv` | `conv(string T, integer, integer) -> string` | `SELECT conv('2C', 16, 10), conv(1111, 2, 10)` | +| `crc32` | `crc32(string) -> string` | `SELECT crc32('MySQL')` | +| `divide` | `divide(number T, number T) -> T` | `SELECT divide(1, 0.5)` | +| `e` | `e() -> double` | `SELECT e()` | +| `exp` | `exp(number T) -> double` | `SELECT exp(0.5)` | +| `expm1` | `expm1(number T) -> double` | `SELECT expm1(0.5)` | +| `floor` | `floor(number T) -> long` | `SELECT floor(0.5)` | +| `ln` | `ln(number T) -> double` | `SELECT ln(10)` | +| `log` | `log(number T) -> double` 或 `log(number T, number T) -> double` | `SELECT log(10)`、`SELECT log(2, 16)` | +| `log2` | `log2(number T) -> double` | `SELECT log2(10)` | +| `log10` | `log10(number T) -> double` | `SELECT log10(10)` | +| `mod` | `mod(number T, number T) -> T` | `SELECT mod(2, 3)` | +| `modulus` | `modulus(number T, number T) -> T` | `SELECT modulus(2, 3)` | +| `multiply` | `multiply(number T, number T) -> T` | `SELECT multiply(2, 3)` | +| `pi` | `pi() -> double` | `SELECT pi()` | +| `pow` | `pow(number T, number T) -> double` | `SELECT pow(2, 3)` | +| `power` | `power(number T, number T) -> double` | `SELECT power(2, 3)` | +| `rand` | `rand() -> float` 或 `rand(number T) -> float` | `SELECT rand()`、`SELECT rand(0.5)` | +| `rint` | `rint(number T) -> double` | `SELECT rint(1.5)` | +| `round` | `round(number T) -> T` 或 `round(number T, integer) -> T` | `SELECT round(1.5)`、`SELECT round(1.175, 2)` | +| `sign` | `sign(number T) -> integer` | `SELECT sign(1.5)` | +| `signum` | `signum(number T) -> integer` | `SELECT signum(0.5)` | +| `sqrt` | `sqrt(number T) -> double` | `SELECT sqrt(0.5)` | +| `strcmp` | `strcmp(string T, string T) -> integer` | `SELECT strcmp('hello', 'hello world')` | +| `subtract` | `subtract(number T, number T) -> T` | `SELECT subtract(3, 2)` | +| `truncate` | `truncate(number T, number T) -> T` | `SELECT truncate(56.78, 1)` | +| `+` | `number T + number T -> T` | `SELECT 1 + 5` | +| `-` | `number T - number T -> T` | `SELECT 3 - 2` | +| `*` | `number T * number T -> T` | `SELECT 2 * 3` | +| `/` | `number T / number T -> T` | `SELECT 1 / 0.5` | +| `%` | `number T % number T -> T` | `SELECT 2 % 3` | + +## 三角函数 + +| 函数 | 规范 | 示例 | +|:----------|:--------------------------------------|:-----------------------| +| `acos` | `acos(number T) -> double` | `SELECT acos(0.5)` | +| `asin` | `asin(number T) -> double` | `SELECT asin(0.5)` | +| `atan` | `atan(number T) -> double` | `SELECT atan(0.5)` | +| `atan2` | `atan2(number T, number T) -> double` | `SELECT atan2(1, 0.5)` | +| `cos` | `cos(number T) -> double` | `SELECT cos(0.5)` | +| `cosh` | `cosh(number T) -> double` | `SELECT cosh(0.5)` | +| `cot` | `cot(number T) -> double` | `SELECT cot(0.5)` | +| `degrees` | `degrees(number T) -> double` | `SELECT degrees(0.5)` | +| `radians` | `radians(number T) -> double` | `SELECT radians(0.5)` | +| `sin` | `sin(number T) -> double` | `SELECT sin(0.5)` | +| `sinh` | `sinh(number T) -> double` | `SELECT sinh(0.5)` | +| `tan` | `tan(number T) -> double` | `SELECT tan(0.5)` | + +## 日期和时间函数 +标有 * 的函数仅在 SQL 中可用。 + +| 函数 | 规范 | 示例 | +|:---------------------|:---------------------------------------------------------------------------------------|:------------------------------------------------------------------------------------| +| `adddate` | `adddate(date, INTERVAL expr unit) -> date` | `SELECT adddate(date('2020-08-26'), INTERVAL 1 hour)` | +| `addtime` | `addtime(date, date) -> date` | `SELECT addtime(date('2008-12-12'), date('2008-12-12'))` | +| `convert_tz` | `convert_tz(date, string, string) -> date` | `SELECT convert_tz('2008-12-25 05:30:00', '+00:00', 'America/Los_Angeles')` | +| `curtime` | `curtime() -> time` | `SELECT curtime()` | +| `curdate` | `curdate() -> date` | `SELECT curdate()` | +| `current_date` | `current_date() -> date` | `SELECT current_date()` | +| `current_time` | `current_time() -> time` | `SELECT current_time()` | +| `current_timestamp` | `current_timestamp() -> date` | `SELECT current_timestamp()` | +| `date` | `date(date) -> date` | `SELECT date('2000-01-02')` | +| `datediff` | `datediff(date, date) -> integer` | `SELECT datediff(date('2000-01-02'), date('2000-01-01'))` | +| `datetime` | `datetime(string) -> datetime` | `SELECT datetime('2008-12-25 00:00:00')` | +| `date_add` | `date_add(date, INTERVAL integer UNIT)` | `SELECT date_add('2020-08-26', INTERVAL 1 HOUR)` | +| `date_format` | `date_format(date, string) -> string` 或 `date_format(date, string, string) -> string` | `SELECT date_format(date('2020-08-26'), 'Y')` | +| `date_sub` | `date_sub(date, INTERVAL expr unit) -> date` | `SELECT date_sub(date('2008-01-02'), INTERVAL 31 day)` | +| `dayofmonth` | `dayofmonth(date) -> integer` | `SELECT dayofmonth(date('2001-05-07'))` | +| `day` | `day(date) -> integer` | `SELECT day(date('2020-08-25'))` | +| `dayname` | `dayname(date) -> string` | `SELECT dayname(date('2020-08-26'))` | +| `dayofmonth` | `dayofmonth(date) -> integer` | `SELECT dayofmonth(date('2020-08-26'))` | +| `dayofweek` | `dayofweek(date) -> integer` | `SELECT dayofweek(date('2020-08-26'))` | +| `dayofyear` | `dayofyear(date) -> integer` | `SELECT dayofyear(date('2020-08-26'))` | +| `dayofweek` | `dayofweek(date) -> integer` | `SELECT dayofweek(date('2020-08-26'))` | +| `day_of_month`\* | `day_of_month(date) -> integer` | `SELECT day_of_month(date('2020-08-26'))` | +| `day_of_week`\* | `day_of_week(date) -> integer` | `SELECT day_of_week(date('2020-08-26'))` | +| `day_of_year`\* | `day_of_year(date) -> integer` | `SELECT day_of_year(date('2020-08-26'))` | +| `extract`\* | `extract(part FROM date) -> integer` | `SELECT extract(MONTH FROM datetime('2020-08-26 10:11:12'))` | +| `from_days` | `from_days(N) -> integer` | `SELECT from_days(733687)` | +| `from_unixtime` | `from_unixtime(N) -> date` | `SELECT from_unixtime(1220249547)` | +| `get_format` | `get_format(PART, string) -> string` | `SELECT get_format(DATE, 'USA')` | +| `hour` | `hour(time) -> integer` | `SELECT hour(time '01:02:03')` | +| `hour_of_day`\* | `hour_of_day(time) -> integer` | `SELECT hour_of_day(time '01:02:03')` | +| `last_day`\* | `last_day(date) -> integer` | `SELECT last_day(date('2020-08-26'))` | +| `localtime` | `localtime() -> date` | `SELECT localtime()` | +| `localtimestamp` | `localtimestamp() -> date` | `SELECT localtimestamp()` | +| `makedate` | `makedate(double, double) -> date` | `SELECT makedate(1945, 5.9)` | +| `maketime` | `maketime(integer, integer, integer) -> date` | `SELECT maketime(1, 2, 3)` | +| `microsecond` | `microsecond(expr) -> integer` | `SELECT microsecond(time '01:02:03.123456')` | +| `minute` | `minute(expr) -> integer` | `SELECT minute(time '01:02:03')` | +| `minute_of_day`\* | `minute_of_day(expr) -> integer` | `SELECT minute_of_day(time '01:02:03')` | +| `minute_of_hour`\* | `minute_of_hour(expr) -> integer` | `SELECT minute_of_hour(time '01:02:03')` | +| `month` | `month(date) -> integer` | `SELECT month(date('2020-08-26'))` | +| `month_of_year`\* | `month_of_year(date) -> integer` | `SELECT month_of_year(date('2020-08-26'))` | +| `monthname` | `monthname(date) -> string` | `SELECT monthname(date('2020-08-26'))` | +| `now` | `now() -> date` | `SELECT now()` | +| `period_add` | `period_add(integer, integer)` | `SELECT period_add(200801, 2)` | +| `period_diff` | `period_diff(integer, integer)` | `SELECT period_diff(200802, 200703)` | +| `quarter` | `quarter(date) -> integer` | `SELECT quarter(date('2020-08-26'))` | +| `second` | `second(time) -> integer` | `SELECT second(time '01:02:03')` | +| `second_of_minute`\* | `second_of_minute(time) -> integer` | `SELECT second_of_minute(time '01:02:03')` | +| `sec_to_time`\* | `sec_to_time(integer) -> date` | `SELECT sec_to_time(10000)` | +| `subdate` | `subdate(date, INTERVAL expr unit) -> date, datetime` | `SELECT subdate(date('2008-01-02'), INTERVAL 31 day)` | +| `subtime` | `subtime(date, date) -> date` | `SELECT subtime(date('2008-12-12'), date('2008-11-15'))` | +| `str_to_date`\* | `str_to_date(string, format) -> date` | `SELECT str_to_date("01,5,2013", "%d,%m,%Y")` | +| `time` | `time(expr) -> time` | `SELECT time('13:49:00')` | +| `timediff` | `timediff(time, time) -> time` | `SELECT timediff(time('23:59:59'), time('13:00:00'))` | +| `timestamp` | `timestamp(date) -> date` | `SELECT timestamp('2001-05-07 00:00:00')` | +| `timestampadd` | `timestampadd(interval, integer, date) -> date)` | `SELECT timestampadd(DAY, 17, datetime('2000-01-01 00:00:00'))` | +| `timestampdiff` | `timestampdiff(interval, date, date) -> integer` | `SELECT timestampdiff(YEAR, '1997-01-01 00:00:00', '2001-03-06 00:00:00')` | +| `time_format` | `time_format(date, string) -> string` | `SELECT time_format('1998-01-31 13:14:15.012345', '%f %H %h %I %i %p %r %S %s %T')` | +| `time_to_sec` | `time_to_sec(time) -> long` | `SELECT time_to_sec(time '22:23:00')` | +| `to_days` | `to_days(date) -> long` | `SELECT to_days(date '2008-10-07')` | +| `to_seconds` | `to_seconds(date) -> integer` | `SELECT to_seconds(date('2008-10-07'))` | +| `unix_timestamp` | `unix_timestamp(date) -> double` | `SELECT unix_timestamp(timestamp('1996-11-15 17:05:42'))` | +| `utc_date` | `utc_date() -> date` | `SELECT utc_date()` | +| `utc_time` | `utc_time() -> date` | `SELECT utc_time()` | +| `utc_timestamp` | `utc_timestamp() -> date` | `SELECT utc_timestamp()` | +| `week` | `week(date[mode]) -> integer` | `SELECT week(date('2008-02-20'))` | +| `weekofyear` | `weekofyear(date[mode]) -> integer` | `SELECT weekofyear(date('2008-02-20'))` | +| `week_of_year`\* | `week_of_year(date[mode]) -> integer` | `SELECT week_of_year(date('2008-02-20'))` | +| `year` | `year(date) -> integer` | `SELECT year(date('2001-07-05'))` | +| `yearweek`\* | `yearweek(date[mode]) -> integer` | `SELECT yearweek(date('2008-02-20'))` | + +## 字符串函数 + +| 函数 | 规范 | 示例 | +|:------------|:------------------------------------------------------------------------------------|:---------------------------------------------------------------| +| `ascii` | `ascii(string) -> integer` | `SELECT ascii('h')` | +| `concat` | `concat(string, string) -> string` | `SELECT concat('hello', 'world')` | +| `concat_ws` | `concat_ws(separator, string, string…) -> string` | `SELECT concat_ws(" ", "Hello", "World!")` | +| `left` | `left(string, integer) -> string` | `SELECT left('hello', 2)` | +| `length` | `length(string) -> integer` | `SELECT length('hello')` | +| `locate` | `locate(string, string, integer) -> integer` 或 `locate(string, string) -> integer` | `SELECT locate('o', 'hello')`、`locate('l', 'hello world', 5)` | +| `replace` | `replace(string, string, string) -> string` | `SELECT replace('hello', 'l', 'x')` | +| `right` | `right(string, integer) -> string` | `SELECT right('hello', 2)` | +| `rtrim` | `rtrim(string) -> string` | `SELECT rtrim('hello ')` | +| `substring` | `substring(string, integer, integer) -> string` | `SELECT substring('hello', 2, 4)` | +| `trim` | `trim(string) -> string` | `SELECT trim(' hello')` | +| `upper` | `upper(string) -> string` | `SELECT upper('hello world')` | + +## 聚合函数 + +| 函数 | 规范 | 示例 | +|:---------|:-------------------------|:-----------------------------------| +| `avg` | `avg(number T) -> T` | `SELECT avg(column) FROM my-index` | +| `count` | `count(number T) -> T` | `SELECT count(date) FROM my-index` | +| `min` | `min(number T) -> T` | `SELECT min(column) FROM my-index` | +| `show` | `show(string) -> string` | `SHOW TABLES LIKE my-index` | + +## 高级函数 + +| 函数 | 规范 | 示例 | +|:---------|:-------------------------------------------|:----------------------------------------| +| `if` | `if(boolean, os_type, os_type) -> os_type` | `SELECT if(false, 0, 1),if(true, 0, 1)` | +| `ifnull` | `ifnull(os_type, os_type) -> os_type` | `SELECT ifnull(0, 1), ifnull(null, 1)` | +| `isnull` | `isnull(os_type) -> integer` | `SELECT isnull(null), isnull(1)` | + +## 基于相关性的搜索(全文搜索) + +这些函数仅可在 `WHERE` 子句中使用。有关它们在 SQL 和 PPL 中的说明和用法示例,请参阅[全文搜索](/search-plugins/sql/full-text)。 diff --git a/i18n/zh/search-plugins/sql/identifiers.md b/i18n/zh/search-plugins/sql/identifiers.md new file mode 100644 index 00000000..9a3ac4fa --- /dev/null +++ b/i18n/zh/search-plugins/sql/identifiers.md @@ -0,0 +1,67 @@ +--- +title: 标识符 +--- + +# 标识符 + +标识符(identifier)是用来命名数据库对象的 ID,例如索引(Index)名称、字段(Field)名称、别名(Alias)等。 +OpenSearch 支持两种标识符:常规标识符和带分隔符的标识符。 + +## 常规标识符 + +常规标识符是以 ASCII 字母(小写或大写)开头的字符串。 +后续字符可以是字母、数字或下划线(_)。它不能是保留关键字。 +也不允许包含空白字符和其他特殊字符。 + +OpenSearch 支持以下常规标识符: + +1. 以点号 `.` 为前缀的标识符。用于隐藏索引,例如 `.opensearch-dashboards`。 +2. 以 `@` 符号为前缀的标识符。用于 Logstash 摄取时生成的元字段。 +3. 中间带有连字符 `-` 的标识符。用于包含日期信息的索引名称。 +4. 包含星号 `*` 的标识符。用于通配符匹配索引模式。 + +对于常规标识符,可以直接使用名称,无需任何反引号或转义字符。 +在本示例中,`source`、`fields`、`account_number`、`firstname` 和 `lastname` 都是标识符。其中,`source` 字段是保留标识符。 + +```sql +SELECT account_number, firstname, lastname FROM accounts; +``` + +| account_number | firstname | lastname | +:--- | :--- | +| 1 | Amber | Duke +| 6 | Hattie | Bond +| 13 | Nanette | Bates +| 18 | Dale | Adams + +## 带分隔符的标识符 + +带分隔符的标识符可以包含常规标识符中不允许出现的特殊字符。 +必须用反引号(\`\`)将带分隔符的标识符括起来。反引号用于将标识符与特殊字符区分开。 + +如果索引名称中包含点号(`.`),例如 `log-2021.01.11`,请使用带反引号的分隔标识符对其进行转义:\``log-2021.01.11`\`。 + +带分隔符的标识符的典型用法: + +1. 包含保留关键字的标识符。 +2. 包含 `.` 的标识符。同样,也适用于用 `-` 包含日期信息的标识符。 +3. 包含其他特殊字符的标识符,例如 Unicode 字符。 + +用反引号引用索引名称: + +```sql +source=`accounts` | fields `account_number`; +``` + +| account_number | +:--- | +| 1 | +| 6 | +| 13 | +| 18 | + +## 大小写敏感性 + +标识符区分大小写。它们必须与 OpenSearch 中存储的名称完全一致。 + +例如,如果运行 `source=Accounts`,你会收到索引不存在的异常,因为实际的索引名称是小写的。 diff --git a/i18n/zh/search-plugins/sql/index.md b/i18n/zh/search-plugins/sql/index.md new file mode 100644 index 00000000..1bbb4410 --- /dev/null +++ b/i18n/zh/search-plugins/sql/index.md @@ -0,0 +1,15 @@ +--- +title: SQL 和 PPL +--- + +# SQL 和 PPL + +借助 OpenSearch SQL,你可以使用 SQL 编写查询(Query),而不必使用 [OpenSearch 查询领域特定语言(DSL)](/query-dsl/full-text/)。 + +## 后续步骤 + +- 了解 [SQL 和 PPL API](/search-plugins/sql/sql-ppl-api)。 +- 了解[在 OpenSearch 中使用 SQL](/search-plugins/sql/sql/)。 +- 了解[在 OpenSearch 中使用 PPL](/search-plugins/sql/ppl/)。 +- 了解[在 OpenSearch Dashboards 中使用 Query Workbench 执行 SQL 和 PPL 查询](/dashboards/query-workbench)。 +- 在[开发者指南](https://github.com/opensearch-project/sql/blob/main/DEVELOPER_GUIDE.rst)中进一步了解 OpenSearch SQL。 diff --git a/i18n/zh/search-plugins/sql/limitation.md b/i18n/zh/search-plugins/sql/limitation.md new file mode 100644 index 00000000..297123e2 --- /dev/null +++ b/i18n/zh/search-plugins/sql/limitation.md @@ -0,0 +1,95 @@ +--- +title: 限制 +--- + +# 限制 + +SQL 插件(plugin)有以下限制: + +## 不支持对表达式进行聚合 + +只能对字段(Field)应用聚合(Aggregation)。聚合不能接受表达式作为参数。例如,不支持 `avg(log(age))`。 + +## FROM 子句中的子查询 + +`FROM` 子句中采用 `SELECT outer FROM (SELECT inner)` 格式的子查询,只有在能够合并为一个查询时才受支持。例如,以下查询是受支持的: + +```sql +SELECT t.f, t.d +FROM ( + SELECT FlightNum as f, DestCountry as d + FROM opensearch_dashboards_sample_data_flights + WHERE OriginCountry = 'US') t +``` + +但如果外层查询包含 `GROUP BY` 或 `ORDER BY`,则不受支持。 + +## JOIN 不支持对连接结果进行聚合 + +`join` 查询不支持对连接结果进行聚合。 +例如,不支持 `SELECT depo.name, avg(empo.age) FROM empo JOIN depo WHERE empo.id == depo.id GROUP BY depo.name`。 + +## 分页仅支持基本查询 + +分页(pagination)查询可以返回分页的响应。 + +目前,分页仅支持基本查询。例如,以下查询会返回带有游标(cursor)ID 的数据。 + +```json +POST _plugins/_sql/ +{ + "fetch_size" : 5, + "query" : "SELECT OriginCountry, DestCountry FROM opensearch_dashboards_sample_data_flights ORDER BY OriginCountry ASC" +} +``` + +带有游标 ID 的 JDBC 格式响应如下。 + +```json +{ + "schema": [ + { + "name": "OriginCountry", + "type": "keyword" + }, + { + "name": "DestCountry", + "type": "keyword" + } + ], + "cursor": "d:eyJhIjp7fSwicyI6IkRYRjFaWEo1UVc1a1JtVjBZMmdCQUFBQUFBQUFCSllXVTJKVU4yeExiWEJSUkhsNFVrdDVXVEZSYkVKSmR3PT0iLCJjIjpbeyJuYW1lIjoiT3JpZ2luQ291bnRyeSIsInR5cGUiOiJrZXl3b3JkIn0seyJuYW1lIjoiRGVzdENvdW50cnkiLCJ0eXBlIjoia2V5d29yZCJ9XSwiZiI6MSwiaSI6ImtpYmFuYV9zYW1wbGVfZGF0YV9mbGlnaHRzIiwibCI6MTMwNTh9", + "total": 13059, + "datarows": [[ + "AE", + "CN" + ]], + "size": 1, + "status": 200 +} +``` + +目前,带有 `aggregation` 和 `join` 的查询不支持分页。 + +## 查询处理引擎 + +SQL 插件有两个查询处理引擎:`V1` 和 `V2`。大多数功能两个引擎都支持,但只有新引擎还在积极开发中。查询会先在 `V2` 引擎上执行,失败时回退到 `V1` 引擎。如果某个查询在 `V2` 中受支持但 `V1` 中没有,则该查询会失败并返回错误响应。 + +### V1 引擎的限制 + +* 不支持不带 `FROM` 子句的字面量 select 表达式。例如,不支持 `SELECT 1`。 +* `WHERE` 子句不支持表达式。例如,不支持 `SELECT FlightNum FROM opensearch_dashboards_sample_data_flights where (AvgTicketPrice + 100) <= 1000`。 +* 大多数[相关性搜索函数](/search-plugins/sql/full-text)仅在 `V2` 引擎中实现。 + +除非包含 `V1` 特有的函数,否则这类查询都能由 `V2` 引擎成功执行。你很可能永远不会遇到这些限制。 + +### V2 引擎的限制 + +* [游标功能](#pagination-only-supports-basic-queries)仅由 `V1` 引擎支持。 + * 关于 `V2` 引擎对 `cursor`/`pagination` 的支持,请关注 [GitHub issue #656](https://github.com/opensearch-project/sql/issues/656)。 +* `json` 格式的输出仅由 `V1` 引擎支持。 +* `V2` 引擎不跟踪查询执行时间,因此不会报告慢查询。 +* `V2` 查询引擎不仅在 OpenSearch 引擎中运行查询,还支持对复杂查询进行后处理。因此,`explain` 的输出不再只是 OpenSearch 领域特定语言(DSL),还包含来自 `V2` 查询引擎的查询计划信息。 +Suggested change +* `V2` 查询引擎不支持 `histogram`、`date_histogram`、`percentiles`、`topHits`、`stats`、`extended_stats`、`terms` 或 `range` 等聚合查询。 +* 不支持 JOIN 和子查询。如需了解 JOIN 和子查询的最新开发进展,请关注 [GitHub issue #1441](https://github.com/opensearch-project/sql/issues/1441) 和 [GitHub issue #892](https://github.com/opensearch-project/sql/issues/892)。 +* 不支持 `nested` 查询的 PartiQL 语法。此外,对象数组和基本类型数组会返回数组的第一个元素,而在 `V1` 中会以 JSON 对象的形式返回整个数组。 diff --git a/i18n/zh/search-plugins/sql/monitoring.md b/i18n/zh/search-plugins/sql/monitoring.md new file mode 100644 index 00000000..d60e0509 --- /dev/null +++ b/i18n/zh/search-plugins/sql/monitoring.md @@ -0,0 +1,45 @@ +--- +title: 监控 +--- + +# 监控 + +通过统计端点,你可以收集插件(plugin)在统计间隔内的指标。注意,目前只实现了 +节点级别的统计信息收集。也就是说,你只能获取当前所访问 +节点的指标。集群级别的统计信息尚未 +实现。 + +## 节点统计信息 + +### 说明 + +响应中各字段的含义如下: + +| 字段名| 说明| +| ------------------------- | ------------------------------------------------------------- | +| request_total| 请求总数| +| request_count| 统计间隔内的请求总数| +|failed_request_count_syserr|统计间隔内因系统错误而失败的请求数| +|failed_request_count_cuserr| 统计间隔内因错误请求而失败的请求数| +| failed_request_count_cb| 表示插件在统计间隔内是否触发了熔断| + +### 示例 + +SQL 查询: + +```console +>> curl -H 'Content-Type: application/json' -X GET localhost:9200/_plugins/_sql/stats +``` + +结果集: + +```json +{ + "failed_request_count_cb": 0, + "failed_request_count_cuserr": 0, + "circuit_breaker": 0, + "request_total": 0, + "request_count": 0, + "failed_request_count_syserr": 0 +} +``` diff --git a/i18n/zh/search-plugins/sql/ppl/functions.md b/i18n/zh/search-plugins/sql/ppl/functions.md new file mode 100644 index 00000000..d2b0a783 --- /dev/null +++ b/i18n/zh/search-plugins/sql/ppl/functions.md @@ -0,0 +1,762 @@ +--- +title: 命令 +--- + +# 命令 + +`PPL` 支持所有 [`SQL` 通用](/search-plugins/sql/functions)函数(function),包括[相关性搜索](/search-plugins/sql/full-text),同时还引入了一些仅在 `PPL` 中可用的函数(称为 `commands`,即命令)。 + +## dedup + +`dedup`(数据去重)命令会从搜索结果中删除按某个字段(Field)判定为重复的文档(Document)。 + +### 语法 + +```sql +dedup [int] [keepempty=] [consecutive=] +``` + +字段 | 说明 | 类型 | 必需 | 默认值 +:--- | :--- |:--- |:--- |:--- +`int` | 为每种组合保留指定数量的重复事件。该数字必须大于 0。如果不指定数字,则只保留第一个出现的事件,其他所有重复项都会从结果中删除。 | `string` | 否 | 1 +`keepempty` | 如果为 true,则当字段列表中的任一字段为 null 值或缺失字段时,保留该文档。 | `nested list of objects` | 否 | False +`consecutive` | 如果为 true,则只删除值组合重复的连续事件。 | `Boolean` | 否 | False +`field-list` | 指定以逗号分隔的字段列表。至少需要一个字段。 | `String` 或以逗号分隔的字符串列表 | 是 | - + +**示例 1:按一个字段去重** + +删除性别相同的重复文档: + +```sql +search source=accounts | dedup gender | fields account_number, gender; +``` + +| account_number | gender +:--- | :--- | +1 | M +13 | F + +**示例 2:保留两个重复文档** + +保留两个性别相同的重复文档: + +```sql +search source=accounts | dedup 2 gender | fields account_number, gender; +``` + +| account_number | gender +:--- | :--- | +1 | M +6 | M +13 | F + +**示例 3:默认保留或忽略空字段** + +保留字段值为 `null` 的重复文档: + +```sql +search source=accounts | dedup email keepempty=true | fields account_number, email; +``` + +| account_number | email +:--- | :--- | +1 | amberduke@pyrami.com +6 | hattiebond@netagy.com +13 | null +18 | daleadams@boink.com + +删除字段值为 `null` 的重复文档: + +```sql +search source=accounts | dedup email | fields account_number, email; +``` + +| account_number | email +:--- | :--- | +1 | amberduke@pyrami.com +6 | hattiebond@netagy.com +18 | daleadams@boink.com + +**示例 4:对连续文档去重** + +删除连续文档中的重复项: + +```sql +search source=accounts | dedup gender consecutive=true | fields account_number, gender; +``` + +| account_number | gender +:--- | :--- | +1 | M +13 | F +18 | M + +### 限制 + +`dedup` 命令不会被重写为 OpenSearch DSL,它只在协调节点上执行。 + +## eval + +`eval` 命令对表达式求值,并将结果追加到搜索结果中。 + +### 语法 {#syntax-1} + +```sql +eval = ["," = ]... +``` + +字段 | 说明 | 必需 +:--- | :--- |:--- +`field` | 如果字段名不存在,则添加一个新字段。如果字段名已存在,则覆盖该字段。 | 是 +`expression` | 指定任意受支持的表达式。 | 是 + +**示例 1:创建新字段** + +为每个文档创建一个新的 `doubleAge` 字段。`doubleAge` 是 `age` 乘以 2 的结果: + +```sql +search source=accounts | eval doubleAge = age * 2 | fields age, doubleAge; +``` + +| age | doubleAge +:--- | :--- | +32 | 64 +36 | 72 +28 | 56 +33 | 66 + +*示例 2*:覆盖现有字段 + +用 `age` 加 1 的结果覆盖 `age` 字段: + +```sql +search source=accounts | eval age = age + 1 | fields age; +``` + +| age +:--- | +| 33 +| 37 +| 29 +| 34 + +**示例 3:使用 `eval` 命令中定义的字段创建新字段** + +创建一个新字段 `ddAge`。`ddAge` 是 `doubleAge` 乘以 2 的结果,其中 `doubleAge` 在 `eval` 命令中定义: + +```sql +search source=accounts | eval doubleAge = age * 2, ddAge = doubleAge * 2 | fields age, doubleAge, ddAge; +``` + +| age | doubleAge | ddAge +:--- | :--- | +| 32 | 64 | 128 +| 36 | 72 | 144 +| 28 | 56 | 112 +| 33 | 66 | 132 + +### 限制 + +``eval`` 命令不会被重写为 OpenSearch DSL,它只在协调节点上执行。 + +## fields + +使用 `fields` 命令在搜索结果中保留或删除字段。 + +### 语法 {#syntax-2} + +```sql +fields [+|-] +``` + +字段 | 说明 | 必需 | 默认值 +:--- | :--- |:---|:--- +`index` | 加号(+)只保留字段列表中指定的字段。减号(-)删除字段列表中指定的所有字段。 | 否 | + +`field list` | 指定以逗号分隔的字段列表。 | 是 | 无默认值 + +**示例 1:从结果中选择指定字段** + +从搜索结果中获取 `account_number`、`firstname` 和 `lastname` 字段: + +```sql +search source=accounts | fields account_number, firstname, lastname; +``` + +| account_number | firstname | lastname +:--- | :--- | +| 1 | Amber | Duke +| 6 | Hattie | Bond +| 13 | Nanette | Bates +| 18 | Dale | Adams + +**示例 2:从搜索结果中删除指定字段** + +从搜索结果中删除 `account_number` 字段: + +```sql +search source=accounts | fields account_number, firstname, lastname | fields - account_number; +``` + +| firstname | lastname +:--- | :--- | +| Amber | Duke +| Hattie | Bond +| Nanette | Bates +| Dale | Adams + +## parse + +使用 `parse` 命令通过正则表达式解析文本字段,并将结果追加到搜索结果中。 + +### 语法 {#syntax-3} + +```sql +parse +``` + +字段 | 说明 | 必需 +:--- | :--- |:--- +field | 文本字段。 | 是 +regular-expression | 用于从给定文本字段中提取新字段的正则表达式。如果新字段名已存在,则会替换原字段。 | 是 + +该正则表达式使用 Java 正则引擎匹配每个文档的整个文本字段。表达式中的每个命名捕获组都会成为一个新的 ``STRING`` 字段。 + +**示例 1:创建新字段** + +本示例展示如何为每个文档创建新字段 `host`。`host` 是 `email` 字段中 `@` 之后的主机名。解析 null 字段将返回空字符串。 + +```sql +os> source=accounts | parse email '.+@(?.+)' | fields email, host ; +fetched rows / total rows = 4/4 +``` + +| email | host +:--- | :--- | +| amberduke@pyrami.com | pyrami.com +| hattiebond@netagy.com | netagy.com +| null | null +| daleadams@boink.com | boink.com + +*示例 2*:覆盖现有字段 + +本示例展示如何用去掉门牌号后的内容覆盖现有的 address 字段。 + +```sql +os> source=accounts | parse address '\d+ (?
.+)' | fields address ; +fetched rows / total rows = 4/4 +``` + +| address +:--- | +| Holmes Lane +| Bristol Street +| Madison Street +| Hutchinson Court + +**示例 3:按转换类型后的解析字段进行过滤和排序** + +本示例展示如何对 address 字段中大于 500 的门牌号进行排序。 + +```sql +os> source=accounts | parse address '(?\d+) (?.+)' | where cast(streetNumber as int) > 500 | sort num(streetNumber) | fields streetNumber, street ; +fetched rows / total rows = 3/3 +``` + +| streetNumber | street +:--- | :--- | +| 671 | Bristol Street +| 789 | Madison Street +| 880 | Holmes Lane + +### 限制 {#limitations-1} + +使用 parse 命令时存在以下限制: + +- 由 parse 定义的字段不能再次解析。例如,`source=accounts | parse address '\d+ (?.+)' | parse street '\w+ (?\w+)' ;` 将无法返回任何表达式。 +- 由 parse 定义的字段不能被其他命令覆盖。例如,输入 `source=accounts | parse address '\d+ (?.+)' | eval street='1' | where street='1' ;` 时,由于 `street` 无法被覆盖,`where` 不会匹配任何文档。 +- parse 所使用的文本字段不能被覆盖。例如,输入 `source=accounts | parse address '\d+ (?.+)' | eval address='1' ;` 时,由于 address 被覆盖,`street` 不会被解析。 +- 由 parse 定义的字段在 `stats` 命令中使用之后,不能再进行过滤或排序。例如,在 `source=accounts | parse email '.+@(?.+)' | stats avg(age) by host | where host=pyrami.com ;` 中,`where` 不会解析列出的域名。 + +## rename + +使用 `rename` 命令重命名搜索结果中的一个或多个字段。 + +### 语法 {#syntax-4} + +```sql +rename AS ["," AS ]... +``` + +字段 | 说明 | 必需 +:--- | :--- |:--- +`source-field` | 要重命名的字段的名称。 | 是 +`target-field` | 要重命名成的名称。 | 是 + +**示例 1:重命名一个字段** + +将 `account_number` 字段重命名为 `an`: + +```sql +search source=accounts | rename account_number as an | fields an; +``` + +| an +:--- | +| 1 +| 6 +| 13 +| 18 + +**示例 2:重命名多个字段** + +将 `account_number` 字段重命名为 `an`,并将 `employer` 重命名为 `emp`: + +```sql +search source=accounts | rename account_number as an, employer as emp | fields an, emp; +``` + +| an | emp +:--- | :--- | +| 1 | Pyrami +| 6 | Netagy +| 13 | Quility +| 18 | null + +### 限制 {#limitations-2} + +`rename` 命令不会被重写为 OpenSearch DSL,它只在协调节点上执行。 + +## sort + +使用 `sort` 命令按指定字段对搜索结果排序(sort)。 + +### 语法 {#syntax-5} + +```sql +sort [count] <[+|-] sort-field>... +``` + +字段 | 说明 | 必需 | 默认值 +:--- | :--- |:--- +`count` | 从排序结果中返回的最大结果数。如果 count=0,则返回所有结果。 | 否 | 1000 +`[+|-]` | 使用加号 [+] 按升序排序,使用减号 [-] 按降序排序。 | 否 | 升序 +`sort-field` | 指定要排序的字段。 | 是 | - + +**示例 1:按一个字段排序** + +按 `age` 字段以升序对所有文档排序: + +```sql +search source=accounts | sort age | fields account_number, age; +``` + +| account_number | age | +:--- | :--- | +| 13 | 28 +| 1 | 32 +| 18 | 33 +| 6 | 36 + +**示例 2:按一个字段排序并返回所有结果** + +按 `age` 字段以升序对所有文档排序,并将 count 指定为 0 以返回所有结果: + +```sql +search source=accounts | sort 0 age | fields account_number, age; +``` + +| account_number | age | +:--- | :--- | +| 13 | 28 +| 1 | 32 +| 18 | 33 +| 6 | 36 + +**示例 3:按一个字段降序排序** + +按 `age` 字段以降序对所有文档排序: + +```sql +search source=accounts | sort - age | fields account_number, age; +``` + +| account_number | age | +:--- | :--- | +| 6 | 36 +| 18 | 33 +| 1 | 32 +| 13 | 28 + +**示例 4:指定返回的排序文档数量** + +按 `age` 字段以升序对所有文档排序,并将 count 指定为 2 以返回两个结果: + +```sql +search source=accounts | sort 2 age | fields account_number, age; +``` + +| account_number | age | +:--- | :--- | +| 13 | 28 +| 1 | 32 + +**示例 5:按多个字段排序** + +按 `gender` 字段以升序、按 `age` 字段以降序对所有文档排序: + +```sql +search source=accounts | sort + gender, - age | fields account_number, gender, age; +``` + +| account_number | gender | age | +:--- | :--- | :--- | +| 13 | F | 28 +| 6 | M | 36 +| 18 | M | 33 +| 1 | M | 32 + +## stats + +使用 `stats` 命令对搜索结果进行聚合(Aggregation)。 + +下表列出了聚合函数,并说明了每个函数如何处理 null 值或缺失值: + +函数 | NULL | MISSING +:--- | :--- |:--- +`COUNT` | 不计数 | 不计数 +`SUM` | 忽略 | 忽略 +`AVG` | 忽略 | 忽略 +`MAX` | 忽略 | 忽略 +`MIN` | 忽略 | 忽略 + +### 语法 {#syntax-6} + +``` +stats ... [by-clause]... +``` + +字段 | 说明 | 必需 | 默认值 +:--- | :--- |:--- +`aggregation` | 指定一个统计聚合函数。该函数的参数必须是字段。 | 是 | 1000 +`by-clause` | 指定用于对结果进行分组的一个或多个字段。如果未指定,`stats` 命令只返回一行,即对整个结果集的聚合结果。 | 否 | - + +**示例 1:计算字段的平均值** + +计算所有文档的平均 `age`: + +```sql +search source=accounts | stats avg(age); +``` + +| avg(age) +:--- | +| 32.25 + +**示例 2:按组计算字段的平均值** + +计算按性别分组的平均年龄: + +```sql +search source=accounts | stats avg(age) by gender; +``` + +| gender | avg(age) +:--- | :--- | +| F | 28.0 +| M | 33.666666666666664 + +**示例 3:按组计算字段的平均值和总和** + +计算按性别分组的年龄平均值和总和: + +```sql +search source=accounts | stats avg(age), sum(age) by gender; +``` + +| gender | avg(age) | sum(age) +:--- | :--- | +| F | 28 | 28 +| M | 33.666666666666664 | 101 + +**示例 4:计算字段的最大值** + +计算最大年龄: + +```sql +search source=accounts | stats max(age); +``` + +| max(age) +:--- | +| 36 + +**示例 5:按组计算字段的最大值和最小值** + +计算按性别分组的年龄最大值和最小值: + +```sql +search source=accounts | stats max(age), min(age) by gender; +``` + +| gender | min(age) | max(age) +:--- | :--- | :--- | +| F | 28 | 28 +| M | 32 | 36 + +## where + +使用带布尔表达式的 `where` 命令过滤搜索结果。只有当布尔表达式的计算结果为 true 时,`where` 命令才会返回结果。 + +### 语法 {#syntax-7} + +```sql +where +``` + +字段 | 说明 | 必需 +:--- | :--- |:--- +`bool-expression` | 计算结果为布尔值的表达式。 | 否 + +**示例:按条件过滤结果集** + +从 `accounts` 索引(Index)中获取 `account_number` 为 1 或 gender 为 `F` 的所有文档: + +```sql +search source=accounts | where account_number=1 or gender=\"F\" | fields account_number, gender; +``` + +| account_number | gender +:--- | :--- | +| 1 | M +| 13 | F + +## head + +使用 `head` 命令按指定的搜索顺序返回前 N 个结果。 + +### 语法 {#syntax-8} + +```sql +head [N] +``` + +字段 | 说明 | 必需 | 默认值 +:--- | :--- |:--- +`N` | 指定要返回的结果数量。 | 否 | 10 + +**示例 1:获取前 10 个结果** + +获取前 10 个结果: + +```sql +search source=accounts | fields firstname, age | head; +``` + +| firstname | age +:--- | :--- | +| Amber | 32 +| Hattie | 36 +| Nanette | 28 + +**示例 2:获取前 N 个结果** + +获取前两个结果: + +```sql +search source=accounts | fields firstname, age | head 2; +``` + +| firstname | age +:--- | :--- | +| Amber | 32 +| Hattie | 36 + +### 限制 {#limitations-3} + +`head` 命令不会被重写为 OpenSearch DSL,它只在协调节点上执行。 + +## rare + +使用 `rare` 命令查找字段列表中所有字段最不常见的值。 +对于分组字段的每组不同值,最多返回 10 个结果。 + +### 语法 {#syntax-9} + +```sql +rare [by-clause] +``` + +字段 | 说明 | 必需 +:--- | :--- |:--- +`field-list` | 指定以逗号分隔的字段名列表。 | 否 +`by-clause` | 指定用于对结果进行分组的一个或多个字段。 | 否 + +**示例 1:查找字段中最不常见的值** + +查找性别中最不常见的值: + +```sql +search source=accounts | rare gender; +``` + +| gender +:--- | +| F +| M + +**示例 2:查找按性别分组的最不常见的值** + +查找按性别分组的最不常见的年龄: + +```sql +search source=accounts | rare age by gender; +``` + +| gender | age +:--- | :--- | +| F | 28 +| M | 32 +| M | 33 + +### 限制 {#limitations-4} + +`rare` 命令不会被重写为 OpenSearch DSL,它只在协调节点上执行。 + +## top {#top-command} + +使用 `top` 命令查找字段列表中所有字段最常见的值。 + +### 语法 {#syntax-10} + +```sql +top [N] [by-clause] +``` + +字段 | 说明 | 默认值 +:--- | :--- |:--- +`N` | 指定要返回的结果数量。 | 10 +`field-list` | 指定以逗号分隔的字段名列表。 | - +`by-clause` | 指定用于对结果进行分组的一个或多个字段。 | - + +**示例 1:查找字段中最常见的值** + +查找最常见的性别: + +```sql +search source=accounts | top gender; +``` + +| gender +:--- | +| M +| F + +**示例 2:查找字段中最常见的一个值** + +查找最常见的那个性别: + +```sql +search source=accounts | top 1 gender; +``` + +| gender +:--- | +| M + +**示例 3:查找按性别分组的最常见的值** + +查找按性别分组的最常见的年龄: + +```sql +search source=accounts | top 1 age by gender; +``` + +| gender | age +:--- | :--- | +| F | 28 +| M | 32 + +### 限制 {#limitations-5} + +`top` 命令不会被重写为 OpenSearch DSL,它只在协调节点上执行。 + +## ad + +`ad` 命令将 [ML Commons 插件](/ml-commons-plugin/)中的随机切割森林(Random Cut Forest,RCF)算法应用于 PPL 命令返回的搜索结果。根据输入的不同,该插件会使用两种 RCF 算法:用于处理时间序列数据的固定时间 RCF,以及用于处理非时间序列数据的批量 RCF。 + +### 语法:用于时间序列数据的固定时间 RCF 命令 + +```sql +ad +``` + +字段 | 说明 | 必需 +:--- | :--- |:--- +`shingle_size` | 由最近的若干条记录组成的连续序列。默认值为 8。 | 否 +`time_decay` | 指定在计算异常分数时考虑多久之前的近期数据。默认值为 0.001。 | 否 +`time_field` | 指定 RCF 用作时间序列数据的时间字段。必须是 long 值(例如以毫秒为单位的时间戳),或格式为 "yyyy-MM-dd HH:mm:ss" 的字符串值。| 是 + +### 语法:用于非时间序列数据的批量 RCF 命令 + +```sql +ad +``` + +字段 | 说明 | 必需 +:--- | :--- |:--- +`shingle_size` | 由最近的若干条记录组成的连续序列。默认值为 8。 | 否 +`time_decay` | 指定在计算异常分数时考虑多久之前的近期数据。默认值为 0.001。 | 否 + +**示例 1:使用时间序列数据,从出租车载客数据中检测纽约市的事件** + +本示例训练一个 RCF 模型(model),并使用该模型检测时间序列载客数据中的异常。 + +PPL 查询: + +```sql +os> source=nyc_taxi | fields value, timestamp | AD time_field='timestamp' | where value=10844.0 +``` + +value | timestamp | score | anomaly_grade +:--- | :--- |:--- | :--- +10844.0 | 1404172800000 | 0.0 | 0.0 + +**示例 2:使用非时间序列数据,从出租车载客数据中检测纽约市的事件** + +PPL 查询: + +```sql +os> source=nyc_taxi | fields value | AD | where value=10844.0 +``` + +value | score | anomalous +:--- | :--- |:--- +| 10844.0 | 0.0 | false + +## kmeans + +kmeans 命令将 ML Commons 插件的 kmeans 算法应用于所提供 PPL 命令的搜索结果。 + +### 语法 {#syntax-11} + +```sql +kmeans +``` + +对于 `cluster-number`,输入要将数据点分成的簇的数量。 + +**示例:对 Iris 数据分组** + +本示例展示如何根据每个样本测得的四个特征(萼片和花瓣的长度与宽度)的组合,对三种鸢尾花(Iris setosa、Iris virginica 和 Iris versicolor)进行分类。 + +PPL 查询: + +```sql +os> source=iris_data | fields sepal_length_in_cm, sepal_width_in_cm, petal_length_in_cm, petal_width_in_cm | kmeans centroids=3 +``` + +sepal_length_in_cm | sepal_width_in_cm | petal_length_in_cm | petal_width_in_cm | ClusterID +:--- | :--- |:--- | :--- | :--- +| 5.1 | 3.5 | 1.4 | 0.2 | 1 +| 5.6 | 3.0 | 4.1 | 1.3 | 0 +| 6.7 | 2.5 | 5.8 | 1.8 | 2 diff --git a/i18n/zh/search-plugins/sql/ppl/index.md b/i18n/zh/search-plugins/sql/ppl/index.md new file mode 100644 index 00000000..12a9baec --- /dev/null +++ b/i18n/zh/search-plugins/sql/ppl/index.md @@ -0,0 +1,34 @@ +--- +title: PPL +--- + +# PPL + +管道处理语言(Piped Processing Language,PPL)是一种以顺序、逐步的方式处理数据的查询语言。PPL 使用管道(`|`)运算符把多个命令组合起来,用于查找和检索数据。它是 OpenSearch 中可观测性(Observability)功能的主要查询语言,并支持多数据源查询。 + +## PPL 语法 + +下面的示例展示了 PPL 的基本语法: + +```sql +search source= | | | ... | +``` + +具体的 PPL 语法示例请参阅[语法](/search-plugins/sql/ppl/syntax)。 + +## PPL 命令 + +PPL 通过一系列命令对数据进行过滤、转换和聚合。每个命令的说明和示例请参阅[命令](/search-plugins/sql/ppl/functions)。 + +## 在 OpenSearch 中使用 PPL + +要使用 PPL,必须先安装 OpenSearch Dashboards。PPL 可以在 [Query Workbench 工具](https://playground.opensearch.org/app/opensearch-query-workbench#/)中使用。关于在 OpenSearch 中使用 PPL 的教程,请参阅 [Query Workbench](/dashboards/query-workbench) 文档。 + +## 开发者文档 + +开发者可以在以下资源中找到相关信息: + +- [Piped Processing Language](https://github.com/opensearch-project/piped-processing-language) 规范 +- [OpenSearch PPL 参考手册](https://github.com/opensearch-project/sql/blob/main/docs/user/ppl/index.rst) +- 使用[基于 PPL 的可视化](https://github.com/opensearch-project/dashboards-observability#event-analytics)实现[可观测性](https://github.com/opensearch-project/dashboards-observability/) +- PPL [数据类型](https://github.com/opensearch-project/sql/blob/main/docs/user/ppl/general/datatypes.rst) diff --git a/i18n/zh/search-plugins/sql/ppl/syntax.md b/i18n/zh/search-plugins/sql/ppl/syntax.md new file mode 100644 index 00000000..7d28c31c --- /dev/null +++ b/i18n/zh/search-plugins/sql/ppl/syntax.md @@ -0,0 +1,68 @@ +--- +title: 语法 +--- + +# PPL 语法 + +每个 PPL 查询都以 `search` 命令开头。它指定要从中搜索和检索文档的索引。后续命令可以按任意顺序排列。 + +::: info 注意 +目前,`PPL` 只支持一个 `search` 命令,并且可以省略该命令以简化查询。 +::: + +## 语法 + +```sql +search source= [boolean-expression] +source= [boolean-expression] +``` + +字段 | 描述 | 必需 +:--- | :--- |:--- +`search` | 指定搜索关键词。 | 是 +`index` | 指定要查询的索引。 | 否 +`bool-expression` | 指定一个求值结果为布尔值的表达式。 | 否 + +## 示例 + +**示例 1:在 accounts 索引中搜索** + +在下面的示例中,`search` 命令将 `accounts` 索引作为数据源,并使用 `fields` 和 `where` 命令设置条件: + +```sql +search source=accounts +| where age > 18 +| fields firstname, lastname +``` + +::: info 注意 +在以下示例中,尖括号 `< >` 中的是必需参数,方括号 `[ ]` 中的是可选参数。 +::: + +**示例 2:获取所有文档** + +要获取 `accounts` 索引中的所有文档,将其指定为 `source`: + +```sql +search source=accounts; +``` + +| account_number | firstname | address | balance | gender | city | employer | state | age | email | lastname | +:--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- +| 1 | Amber | 880 Holmes Lane | 39225 | M | Brogan | Pyrami | IL | 32 | amberduke@pyrami.com | Duke +| 6 | Hattie | 671 Bristol Street | 5686 | M | Dante | Netagy | TN | 36 | hattiebond@netagy.com | Bond +| 13 | Nanette | 789 Madison Street | 32838 | F | Nogal | Quility | VA | 28 | null | Bates +| 18 | Dale | 467 Hutchinson Court | 4180 | M | Orick | null | MD | 33 | daleadams@boink.com | Adams + +**示例 3:获取符合条件的文档** + +要获取 `accounts` 索引中 `account_number` 等于 1 或 `gender` 为 `F` 的所有文档,使用以下查询: + +```sql +search source=accounts account_number=1 or gender=\"F\"; +``` + +| account_number | firstname | address | balance | gender | city | employer | state | age | email | lastname | +:--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- +| 1 | Amber | 880 Holmes Lane | 39225 | M | Brogan | Pyrami | IL | 32 | amberduke@pyrami.com | Duke | +| 13 | Nanette | 789 Madison Street | 32838 | F | Nogal | Quility | VA | 28 | null | Bates | diff --git a/i18n/zh/search-plugins/sql/response-formats.md b/i18n/zh/search-plugins/sql/response-formats.md new file mode 100644 index 00000000..172ac6a8 --- /dev/null +++ b/i18n/zh/search-plugins/sql/response-formats.md @@ -0,0 +1,280 @@ +--- +title: 响应格式 +--- + +# 响应格式 + +SQL 插件提供 `jdbc`、`csv`、`raw` 和 `json` 四种响应格式,分别适用于不同的用途。`jdbc` 格式使用最为广泛,因为它提供了 schema 信息,并增加了分页(pagination)等更多功能。除了 JDBC 驱动程序之外,各种客户端也都能从详细且格式规范的响应中受益。 + +## JDBC 格式 + +默认情况下,SQL 插件以标准 JDBC 格式返回响应。该格式面向 JDBC 驱动程序以及需要 schema 和结果集都格式规范的客户端。 + +#### 示例请求 + +以下查询没有指定响应格式,因此格式为 `jdbc`: + +```json +POST _plugins/_sql +{ + "query" : "SELECT firstname, lastname, age FROM accounts ORDER BY age LIMIT 2" +} +``` + +#### 示例响应 + +在响应中,`schema` 包含字段名称和类型,`datarows` 字段包含结果集: + +```json +{ + "schema": [{ + "name": "firstname", + "type": "text" + }, + { + "name": "lastname", + "type": "text" + }, + { + "name": "age", + "type": "long" + } + ], + "total": 4, + "datarows": [ + [ + "Nanette", + "Bates", + 28 + ], + [ + "Amber", + "Duke", + 32 + ] + ], + "size": 2, + "status": 200 +} +``` + +如果发生任何类型的错误,OpenSearch 会返回错误消息。 + +以下查询搜索一个不存在的字段 `unknown`: + +```json +POST /_plugins/_sql +{ + "query" : "SELECT unknown FROM accounts" +} +``` + +响应中包含错误消息和错误原因: + +```json +{ + "error": { + "reason": "Invalid SQL query", + "details": "Field [unknown] cannot be found or used here.", + "type": "SemanticAnalysisException" + }, + "status": 400 +} +``` + +## OpenSearch DSL JSON 格式 + +如果将格式设置为 `json`,将以 JSON 格式返回 OpenSearch 的原始响应。由于这是 OpenSearch 的原生响应,需要额外处理才能解析和理解它。 + +#### 示例请求 {#example-request-1} + +以下查询将响应格式设置为 `json`: + +```json +POST _plugins/_sql?format=json +{ + "query" : "SELECT firstname, lastname, age FROM accounts ORDER BY age LIMIT 2" +} +``` + +#### 示例响应 {#example-response-1} + +响应为 OpenSearch 的原始响应: + +```json +{ + "_shards": { + "total": 5, + "failed": 0, + "successful": 5, + "skipped": 0 + }, + "hits": { + "hits": [{ + "_index": "accounts", + "_type": "account", + "_source": { + "firstname": "Nanette", + "age": 28, + "lastname": "Bates" + }, + "_id": "13", + "sort": [ + 28 + ], + "_score": null + }, + { + "_index": "accounts", + "_type": "account", + "_source": { + "firstname": "Amber", + "age": 32, + "lastname": "Duke" + }, + "_id": "1", + "sort": [ + 32 + ], + "_score": null + } + ], + "total": { + "value": 4, + "relation": "eq" + }, + "max_score": null + }, + "took": 100, + "timed_out": false +} +``` + +## CSV 格式 + +也可以指定以 CSV 格式返回结果。 + +#### 示例请求 {#example-request-2} + +```json +POST /_plugins/_sql?format=csv +{ + "query" : "SELECT firstname, lastname, age FROM accounts ORDER BY age" +} +``` + +#### 示例响应 {#example-response-2} + +```text +firstname,lastname,age +Nanette,Bates,28 +Amber,Duke,32 +Dale,Adams,33 +Hattie,Bond,36 +``` +### 清理 CSV 格式的结果 + +默认情况下,OpenSearch 会按照以下规则清理(sanitize)表头单元格(字段名称)和数据单元格(字段内容): + +- 如果单元格以 `+`、`-`、`=` 或 `@` 开头,清理程序会在单元格开头插入一个单引号(`'`)。 +- 如果单元格包含一个或多个逗号(`,`),清理程序会用双引号(`"`)将单元格括起来。 + +### 示例 + +以下请求索引一个文档,其中的单元格以特殊字符开头或包含逗号: + +```json +PUT /userdata/_doc/1?refresh=true +{ + "+firstname": "-Hattie", + "=lastname": "@Bond", + "address": "671 Bristol Street, Dente, TN" +} +``` + +可以使用下面的查询请求以 CSV 格式返回结果: + +```json +POST /_plugins/_sql?format=csv +{ + "query" : "SELECT * FROM userdata" +} +``` + +在响应中,以特殊字符开头的单元格前面加上了 `'`,包含逗号的单元格则被引号括起来: + +```text +'+firstname,'=lastname,address +'Hattie,'@Bond,"671 Bristol Street, Dente, TN" +``` + +要跳过清理,请将 `sanitize` 查询参数设置为 false: + +```json +POST /_plugins/_sql?format=csvandsanitize=false +{ + "query" : "SELECT * FROM userdata" +} +``` + +响应包含原始 CSV 格式的结果: + +```text +=lastname,address,+firstname +@Bond,"671 Bristol Street, Dente, TN",-Hattie +``` + +## Raw 格式 + +可以使用 raw 格式将结果通过管道传给其他命令行工具做后续处理。 + +#### 示例请求 {#example-request-3} + +```json +POST /_plugins/_sql?format=raw +{ + "query" : "SELECT firstname, lastname, age FROM accounts ORDER BY age" +} +``` + +#### 示例响应 {#example-response-3} + +```text +Nanette|Bates|28 +Amber|Duke|32 +Dale|Adams|33 +Hattie|Bond|36 +``` + +默认情况下,OpenSearch 会按照以下规则清理 `raw` 格式的结果: + +- 如果数据单元格包含一个或多个管道符(`|`),清理程序会用双引号将单元格括起来。 + +### 示例 {#example-1} + +以下请求索引一个字段中包含管道符(`|`)的文档: + +```json +PUT /userdata/_doc/1?refresh=true +{ + "+firstname": "|Hattie", + "=lastname": "Bond|", + "|address": "671 Bristol Street| Dente| TN" +} +``` + +可以使用下面的查询请求以 `raw` 格式返回结果: + +```json +POST /_plugins/_sql?format=raw +{ + "query" : "SELECT * FROM userdata" +} +``` + +查询返回的结果中,包含 `|` 字符的单元格被引号括起来: + +```text +"|address"|=lastname|+firstname +"671 Bristol Street| Dente| TN"|"Bond|"|"|Hattie" +``` diff --git a/i18n/zh/search-plugins/sql/settings.md b/i18n/zh/search-plugins/sql/settings.md new file mode 100644 index 00000000..e5164530 --- /dev/null +++ b/i18n/zh/search-plugins/sql/settings.md @@ -0,0 +1,112 @@ +--- +title: 设置 +--- + +# SQL 设置 + +SQL 插件在标准的 OpenSearch 集群设置之外新增了几项设置。其中大多数是动态设置,因此无需重启集群即可更改插件的默认行为。关于静态设置和动态设置的更多信息,请参阅[配置 OpenSearch](/install-and-configure/configuring-opensearch/)。 + +可以分别禁用 `PPL` 查询或 `SQL` 查询的处理。 + +可以像更新其他集群设置一样更新这些设置: + +```json +PUT _cluster/settings +{ + "transient" : { + "plugins.sql.enabled" : false + } +} +``` + +也可以使用以下请求格式: + +```json +PUT _cluster/settings +{ + "transient": { + "plugins": { + "ppl": { + "enabled": "false" + } + } + } +} +``` + +同样,也可以向 `_plugins/_query/settings` 端点发送请求来更新设置: + +```json +PUT _plugins/_query/settings +{ + "transient" : { + "plugins.sql.enabled" : false + } +} +``` + +也可以使用以下请求格式: + +```json +PUT _plugins/_query/settings +{ + "transient": { + "plugins": { + "ppl": { + "enabled": "false" + } + } + } +} +``` + +::: info 注意 +发送到 `_plugins/_ppl` 和 `_plugins/_sql` 端点的请求会在请求体中包含索引名称,因此它们与 `bulk`、`mget` 和 `msearch` 操作有相同的访问策略考量。将 `rest.action.multi.allow_explicit_index` 参数设置为 `false` 会同时禁用 `SQL` 和 `PPL` 端点。 +::: + +## 可用设置 + +设置 | 默认值 | 描述 +:--- | :--- | :--- +`plugins.sql.enabled` | True | 设置为 `false` 可禁用插件中的 `SQL` 支持。 +`plugins.ppl.enabled` | True | 设置为 `false` 可禁用插件中的 `PPL` 支持。 +`plugins.sql.slowlog` | 2 秒 | 配置慢查询的时间阈值(以秒为单位)。插件会在 `opensearch.log` 中以 `Slow query: elapsed=xxx (ms)` 的形式记录慢查询。 +`plugins.sql.cursor.keep_alive` | 1 分钟 | 配置游标(cursor)上下文保持打开的时长。游标上下文占用资源较多,因此建议设置较小的值。 +`plugins.query.memory_limit` | 85% | 配置查询引擎断路器的堆内存使用上限。 +`plugins.query.size_limit` | 200 | 设置查询引擎从 OpenSearch 获取索引数据时的默认大小。 + +## Spark 连接器设置 + +SQL 插件支持将 [Apache Spark](https://spark.apache.org/) 作为增强计算源。当数据源在 Apache Spark 中被定义为表时,OpenSearch 可以使用这些表。这样你就可以在 OpenSearch Dashboards 的 [Discover](/dashboards/discover/index-discover) 和可观测性日志中对外部数据源运行 SQL 查询。 + +首先,启用以下设置,将 Spark 添加为数据源并启用正确的权限。 + +设置 | 描述 +:--- | :--- +`spark.uri` | Spark 数据源的标识符。 +`spark.auth.type` | 用于向 Spark 进行身份验证的授权类型。 +`spark.auth.username` | Spark 数据源的用户名。 +`spark.auth.password` | Spark 数据源的密码。 +`spark.datasource.flint.host` | Spark 数据源的主机。默认值为 `localhost`。 +`spark.datasource.flint.port` | Spark 的端口号。默认值为 `9200`。 +`spark.datasource.flint.scheme` | Spark 查询中使用的数据协议。有效值为 `http` 和 `https`。 +`spark.datasource.flint.auth` | 访问 Spark 数据源所需的授权方式。有效值为 `false` 和 `sigv4`。 +`spark.datasource.flint.region` | OpenSearch 集群所在的 AWS 区域。仅在 `auth` 设置为 `sigv4` 时使用。默认值为 `us-west-2``。 +`spark.datasource.flint.write.id_name` | Spark 连接器写入的索引名称。 +`spark.datasource.flint.ignore.id_column` | 在查询中导出数据时排除 `id` 列。默认值为 `true`。 +`spark.datasource.flint.write.batch_size` | 设置写入 Spark 连接的索引时的批处理大小。默认值为 `1000`。 +`spark.datasource.flint.write.refresh_policy` | 设置连接器向 OpenSearch 写入数据失败时 Spark 连接的刷新策略。可以是不刷新(`false`)、立即刷新(`true`),或者设置一个等待时间 `wait_for: X`。默认值为 `false`。 +`spark.datasource.flint.read.scroll_size` | 设置使用 Spark 运行的查询返回的结果数量。默认值为 `100`。 +`spark.flint.optimizer.enabled` | 使 OpenSearch 针对 Spark 连接进行优化。默认值为 `true`。 +`spark.flint.index.hybridscan.enabled` | 使 OpenSearch 能够从数据源中扫描非分区设备上的写入数据。默认值为 `false`。 + +配置完成后,可以使用以下 API 调用测试 Spark 连接: + +```json +POST /_plugins/_ppl +content-type: application/json + +{ + "query": "source = my_spark.sql('select * from alb_logs')" +} +``` diff --git a/i18n/zh/search-plugins/sql/sql-ppl-api.md b/i18n/zh/search-plugins/sql/sql-ppl-api.md new file mode 100644 index 00000000..e29f89ee --- /dev/null +++ b/i18n/zh/search-plugins/sql/sql-ppl-api.md @@ -0,0 +1,508 @@ +--- +title: SQL 和 PPL API +--- + +# SQL 和 PPL API + +使用 SQL 和 PPL API 向 SQL 插件发送查询。使用 `_sql` 端点发送 SQL 查询,使用 `_ppl` 端点发送 PPL 查询。对于这两种查询,都可以使用 `_explain` 端点将查询转换为 [OpenSearch 领域特定语言](/query-dsl/)(DSL),或者用来排查错误。 + +## 查询 API + +向 SQL 插件发送 SQL/PPL 查询。可以通过查询参数指定响应格式。 + +### 查询参数 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +[format](/search-plugins/sql/response-formats) | String | 响应格式。`_sql` 端点支持 `jdbc`、`csv`、`raw` 和 `json` 格式。`_ppl` 端点支持 `jdbc`、`csv` 和 `raw` 格式。默认值为 `jdbc`。 +sanitize | Boolean | 指定是否对结果中的特殊字符进行转义。更多信息请参阅[响应格式](/search-plugins/sql/response-formats)。默认值为 `true`。 + +### 请求字段 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +query | String | 要执行的查询。必需。 +[filter](#filtering-results) | JSON object | 对结果的过滤条件。可选。 +[fetch_size](#paginating-results) | integer | 单个响应中返回的结果数量,用于对结果分页。默认值为 1,000。可选。仅支持 `jdbc` 响应格式。 + +#### 示例请求 + +```json +POST /_plugins/_sql +{ + "query" : "SELECT * FROM accounts" +} +``` + +#### 示例响应 + +响应包含 schema 和结果: + +```json +{ + "schema": [ + { + "name": "account_number", + "type": "long" + }, + { + "name": "firstname", + "type": "text" + }, + { + "name": "address", + "type": "text" + }, + { + "name": "balance", + "type": "long" + }, + { + "name": "gender", + "type": "text" + }, + { + "name": "city", + "type": "text" + }, + { + "name": "employer", + "type": "text" + }, + { + "name": "state", + "type": "text" + }, + { + "name": "age", + "type": "long" + }, + { + "name": "email", + "type": "text" + }, + { + "name": "lastname", + "type": "text" + } + ], + "datarows": [ + [ + 1, + "Amber", + "880 Holmes Lane", + 39225, + "M", + "Brogan", + "Pyrami", + "IL", + 32, + "amberduke@pyrami.com", + "Duke" + ], + [ + 6, + "Hattie", + "671 Bristol Street", + 5686, + "M", + "Dante", + "Netagy", + "TN", + 36, + "hattiebond@netagy.com", + "Bond" + ], + [ + 13, + "Nanette", + "789 Madison Street", + 32838, + "F", + "Nogal", + "Quility", + "VA", + 28, + "nanettebates@quility.com", + "Bates" + ], + [ + 18, + "Dale", + "467 Hutchinson Court", + 4180, + "M", + "Orick", + null, + "MD", + 33, + "daleadams@boink.com", + "Adams" + ] + ], + "total": 4, + "size": 4, + "status": 200 +} +``` + +### 响应字段 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +schema | Array | 指定所有字段的名称和类型。 +data_rows | 2D array | 结果数组。每个结果表示一个匹配的行(文档)。 +total | Integer | 索引中行(文档)的总数。 +size | Integer | 单个响应中返回的结果数量。 +status | String | OpenSearch 运行查询后返回的 HTTP 响应状态。 + +## Explain API + +SQL 插件提供 `explain` 功能,用于展示查询在 OpenSearch 上是如何执行的,这对于调试和开发很有帮助。向 `_plugins/_sql/_explain` 或 `_plugins/_ppl/_explain` 端点发送 POST 请求,会返回 JSON 格式的 [OpenSearch 领域特定语言](/query-dsl/)(DSL)来解释该查询。 +可以在命令行中使用 `curl` 执行 explain API 操作,也可以像下面的示例那样在 Dashboards 控制台中执行。 + +#### SQL 查询的 explain 请求示例 + +```json +POST _plugins/_sql/_explain +{ + "query": "SELECT firstname, lastname FROM accounts WHERE age > 20" +} +``` + +#### SQL 查询的 explain 响应示例 + +```json +{ + "root": { + "name": "ProjectOperator", + "description": { + "fields": "[firstname, lastname]" + }, + "children": [ + { + "name": "OpenSearchIndexScan", + "description": { + "request": """OpenSearchQueryRequest(indexName=accounts, sourceBuilder={"from":0,"size":200,"timeout":"1m","query":{"range":{"age":{"from":20,"to":null,"include_lower":false,"include_upper":true,"boost":1.0}}},"_source":{"includes":["firstname","lastname"],"excludes":[]},"sort":[{"_doc":{"order":"asc"}}]}, searchDone=false)""" + }, + "children": [] + } + ] + } +} +``` + +#### PPL 查询的 explain 请求示例 + +```json +POST _plugins/_ppl/_explain +{ + "query" : "source=accounts | fields firstname, lastname" +} +``` + +#### PPL 查询的 explain 响应示例 + +```json +{ + "root": { + "name": "ProjectOperator", + "description": { + "fields": "[firstname, lastname]" + }, + "children": [ + { + "name": "OpenSearchIndexScan", + "description": { + "request": """OpenSearchQueryRequest(indexName=accounts, sourceBuilder={"from":0,"size":200,"timeout":"1m","_source":{"includes":["firstname","lastname"],"excludes":[]}}, searchDone=false)""" + }, + "children": [] + } + ] + } +} +``` + +对于需要后处理的查询,`explain` 响应除了 OpenSearch DSL 之外还包含查询计划。对于不需要后处理的查询,可以看到完整的 DSL。 + +## 结果分页 + +要获取分页响应,请使用 `fetch_size` 参数。`fetch_size` 的值应大于 0,默认值为 1,000。值为 0 时将回退为不分页的响应。 + +::: info 注意 +`fetch_size` 参数仅支持 `jdbc` 响应格式。 +::: + +### 示例 + +以下请求包含一个 SQL 查询,并指定每次返回五个结果: + +```json +POST _plugins/_sql/ +{ + "fetch_size" : 5, + "query" : "SELECT firstname, lastname FROM accounts WHERE age > 20 ORDER BY state ASC" +} +``` + +响应包含不带 `fetch_size` 的查询会返回的所有字段,此外还有一个 `cursor` 字段,用于获取后续各页结果: + +```json +{ + "schema": [ + { + "name": "firstname", + "type": "text" + }, + { + "name": "lastname", + "type": "text" + } + ], + "cursor": "d:eyJhIjp7fSwicyI6IkRYRjFaWEo1UVc1a1JtVjBZMmdCQUFBQUFBQUFBQU1XZWpkdFRFRkZUMlpTZEZkeFdsWnJkRlZoYnpaeVVRPT0iLCJjIjpbeyJuYW1lIjoiZmlyc3RuYW1lIiwidHlwZSI6InRleHQifSx7Im5hbWUiOiJsYXN0bmFtZSIsInR5cGUiOiJ0ZXh0In1dLCJmIjo1LCJpIjoiYWNjb3VudHMiLCJsIjo5NTF9", + "total": 956, + "datarows": [ + [ + "Cherry", + "Carey" + ], + [ + "Lindsey", + "Hawkins" + ], + [ + "Sargent", + "Powers" + ], + [ + "Campos", + "Olsen" + ], + [ + "Savannah", + "Kirby" + ] + ], + "size": 5, + "status": 200 +} +``` + +要获取后续页面,请使用上一个响应中的 `cursor`: + +```json +POST /_plugins/_sql +{ + "cursor": "d:eyJhIjp7fSwicyI6IkRYRjFaWEo1UVc1a1JtVjBZMmdCQUFBQUFBQUFBQU1XZWpkdFRFRkZUMlpTZEZkeFdsWnJkRlZoYnpaeVVRPT0iLCJjIjpbeyJuYW1lIjoiZmlyc3RuYW1lIiwidHlwZSI6InRleHQifSx7Im5hbWUiOiJsYXN0bmFtZSIsInR5cGUiOiJ0ZXh0In1dLCJmIjo1LCJpIjoiYWNjb3VudHMiLCJsIjo5NTF9" +} +``` + +下一个响应只包含结果的 `datarows` 和一个新的 `cursor`。 + +```json +{ + "cursor": "d:eyJhIjp7fSwicyI6IkRYRjFaWEo1UVc1a1JtVjBZMmdCQUFBQUFBQUFBQU1XZWpkdFRFRkZUMlpTZEZkeFdsWnJkRlZoYnpaeVVRPT0iLCJjIjpbeyJuYW1lIjoiZmlyc3RuYW1lIiwidHlwZSI6InRleHQifSx7Im5hbWUiOiJsYXN0bmFtZSIsInR5cGUiOiJ0ZXh0In1dLCJmIjo1LCJpIjoiYWNjb3VudHMabcde12345", + "datarows": [ + [ + "Abbey", + "Karen" + ], + [ + "Chen", + "Ken" + ], + [ + "Ani", + "Jade" + ], + [ + "Peng", + "Hu" + ], + [ + "John", + "Doe" + ] + ] +} +``` + +::: info 注意 +如果嵌套字段被展平,`datarows` 中的记录数可能会超过 `fetch_size`。 +::: + +最后一页结果只有 `datarows`,没有 `cursor`。到最后一页时,`cursor` 上下文会被自动清除。 + +要显式清除游标(cursor)上下文,请使用 `_plugins/_sql/close` 端点操作: + +```json +POST /_plugins/_sql/close +{ + "cursor": "d:eyJhIjp7fSwicyI6IkRYRjFaWEo1UVc1a1JtVjBZMmdCQUFBQUFBQUFBQU1XZWpkdFRFRkZUMlpTZEZkeFdsWnJkRlZoYnpaeVVRPT0iLCJjIjpbeyJuYW1lIjoiZmlyc3RuYW1lIiwidHlwZSI6InRleHQifSx7Im5hbWUiOiJsYXN0bmFtZSIsInR5cGUiOiJ0ZXh0In1dLCJmIjo1LCJpIjoiYWNjb3VudHMiLCJsIjo5NTF9" +}' +``` + +响应为 OpenSearch 返回的确认信息: + +```json +{"succeeded":true} +``` + +## 过滤结果 + +可以使用 `filter` 参数直接向 OpenSearch DSL 添加更多条件。 + +以下 SQL 查询返回所有客户的姓名和账户余额,然后对结果进行过滤,只保留余额少于 $10,000 的客户。 + +```json +POST /_plugins/_sql/ +{ + "query" : "SELECT firstname, lastname, balance FROM accounts", + "filter" : { + "range" : { + "balance" : { + "lt" : 10000 + } + } + } +} +``` + +响应包含匹配的结果: + +```json +{ + "schema": [ + { + "name": "firstname", + "type": "text" + }, + { + "name": "lastname", + "type": "text" + }, + { + "name": "balance", + "type": "long" + } + ], + "total": 2, + "datarows": [ + [ + "Hattie", + "Bond", + 5686 + ], + [ + "Dale", + "Adams", + 4180 + ] + ], + "size": 2, + "status": 200 +} +``` + +可以使用 Explain API 查看此查询在 OpenSearch 上是如何执行的: + +```json +POST /_plugins/_sql/_explain +{ + "query" : "SELECT firstname, lastname, balance FROM accounts", + "filter" : { + "range" : { + "balance" : { + "lt" : 10000 + } + } + } +}' +``` + +响应包含与上述查询对应的 OpenSearch DSL 布尔查询: + +```json +{ + "from": 0, + "size": 200, + "query": { + "bool": { + "filter": [{ + "bool": { + "filter": [{ + "range": { + "balance": { + "from": null, + "to": 10000, + "include_lower": true, + "include_upper": false, + "boost": 1.0 + } + } + }], + "adjust_pure_negative": true, + "boost": 1.0 + } + }], + "adjust_pure_negative": true, + "boost": 1.0 + } + }, + "_source": { + "includes": [ + "firstname", + "lastname", + "balance" + ], + "excludes": [] + } +} +``` + +## 使用参数 + +可以使用 `parameters` 字段向预处理(prepared)SQL 查询传递参数值。 + +以下 explain 操作使用了一个带 `age` 参数的 SQL 查询: + +```json +POST /_plugins/_sql/_explain +{ + "query": "SELECT * FROM accounts WHERE age = ?", + "parameters": [{ + "type": "integer", + "value": 30 + }] +} +``` + +响应包含与上述 SQL 查询对应的 OpenSearch DSL 布尔查询: + +```json +{ + "from": 0, + "size": 200, + "query": { + "bool": { + "filter": [{ + "bool": { + "must": [{ + "term": { + "age": { + "value": 30, + "boost": 1.0 + } + } + }], + "adjust_pure_negative": true, + "boost": 1.0 + } + }], + "adjust_pure_negative": true, + "boost": 1.0 + } + } +} + +``` diff --git a/i18n/zh/search-plugins/sql/sql/aggregations.md b/i18n/zh/search-plugins/sql/sql/aggregations.md new file mode 100644 index 00000000..de3d611f --- /dev/null +++ b/i18n/zh/search-plugins/sql/sql/aggregations.md @@ -0,0 +1,260 @@ +--- +title: 聚合函数 +--- + +# 聚合函数 + +聚合函数(aggregate function)作用于由 `GROUP BY` 子句定义的子集。如果没有 `GROUP BY` 子句,聚合函数作用于结果集中的所有元素。可以在 `GROUP BY`、`SELECT` 和 `HAVING` 子句中使用聚合函数。 + +OpenSearch 支持以下聚合函数。 + +函数 | 描述 +:--- | :--- +`AVG` | 返回结果的平均值。 +`COUNT` | 返回结果的数量。 +`SUM` | 返回结果的总和。 +`MIN` | 返回结果的最小值。 +`MAX` | 返回结果的最大值。 +`VAR_POP` 或 `VARIANCE` | 舍弃 null 值后,返回结果的总体方差。只有一行结果时返回 0。 +`VAR_SAMP` | 舍弃 null 值后,返回结果的样本方差。只有一行结果时返回 null。 +`STD` 或 `STDDEV` | 返回结果的样本标准差。只有一行结果时返回 0。 +`STDDEV_POP` | 返回结果的总体标准差。只有一行结果时返回 0。 +`STDDEV_SAMP` | 返回结果的样本标准差。只有一行结果时返回 null。 + +下面的示例引用了一个 `employees` 表。可以使用批量索引操作将以下文档索引到 OpenSearch 中,然后试用这些示例: + +```json +PUT employees/_bulk?refresh +{"index":{"_id":"1"}} +{"employee_id": 1, "department":1, "firstname":"Amber", "lastname":"Duke", "sales":1356, "sale_date":"2020-01-23"} +{"index":{"_id":"2"}} +{"employee_id": 1, "department":1, "firstname":"Amber", "lastname":"Duke", "sales":39224, "sale_date":"2021-01-06"} +{"index":{"_id":"6"}} +{"employee_id":6, "department":1, "firstname":"Hattie", "lastname":"Bond", "sales":5686, "sale_date":"2021-06-07"} +{"index":{"_id":"7"}} +{"employee_id":6, "department":1, "firstname":"Hattie", "lastname":"Bond", "sales":12432, "sale_date":"2022-05-18"} +{"index":{"_id":"13"}} +{"employee_id":13,"department":2, "firstname":"Nanette", "lastname":"Bates", "sales":32838, "sale_date":"2022-04-11"} +{"index":{"_id":"18"}} +{"employee_id":18,"department":2, "firstname":"Dale", "lastname":"Adams", "sales":4180, "sale_date":"2022-11-05"} +``` + +## GROUP BY + +`GROUP BY` 子句定义结果集的子集。聚合函数作用于这些子集,并为每个子集返回一行结果。 + +可以在 `GROUP BY` 子句中使用标识符(identifier)、序号或表达式。 + +### 在 GROUP BY 中使用标识符 + +可以在 `GROUP BY` 子句中指定要聚合的字段名称(列名)。例如,以下查询返回部门编号以及每个部门的销售总额: +```sql +SELECT department, sum(sales) +FROM employees +GROUP BY department; +``` + +| department | sum(sales) +:--- | :--- +1 | 58700 | +2 | 37018 | + +### 在 GROUP BY 中使用序号 + +可以在 `GROUP BY` 子句中指定要聚合的列号。列号由该列在 `SELECT` 子句中的位置决定。例如,以下查询与上面的查询等价,它返回部门编号以及每个部门的销售总额,并按结果集的第一列(即 `department`)对结果分组: + +```sql +SELECT department, sum(sales) +FROM employees +GROUP BY 1; +``` + +| department | sum(sales) +:--- | :--- +1 | 58700 | +2 | 37018 | + +### 在 GROUP BY 中使用表达式 + +可以在 `GROUP BY` 子句中使用表达式。例如,以下查询返回每年的平均销售额: + +```sql +SELECT year(sale_date), avg(sales) +FROM employees +GROUP BY year(sale_date); +``` + +| year(start_date) | avg(sales) +:--- | :--- +| 2020 | 1356.0 | +| 2021 | 22455.0 | +| 2022 | 16484.0 | + +## SELECT + +可以在 `SELECT` 子句中直接使用聚合表达式,也可以将其作为更大表达式的一部分来使用。此外,还可以将表达式用作聚合函数的参数。 + +### 在 SELECT 中直接使用聚合表达式 + +以下查询返回每个部门的平均销售额: + +```sql +SELECT department, avg(sales) +FROM employees +GROUP BY department; +``` + +| department | avg(sales) +:--- | :--- +1 | 14675.0 | +2 | 18509.0 | + +### 在 SELECT 中将聚合表达式作为更大表达式的一部分 + +以下查询按平均销售额的 5% 计算每个部门员工的平均佣金: + +```sql +SELECT department, avg(sales) * 0.05 as avg_commission +FROM employees +GROUP BY department; +``` + +| department | avg_commission +:--- | :--- +1 | 733.75 | +2 | 925.45 | + +### 将表达式用作聚合函数的参数 + +以下查询计算每个部门的平均佣金金额。它先按 `sales` 的 5% 计算每个 `sales` 值对应的佣金金额,然后求出所有佣金值的平均值: + +```sql +SELECT department, avg(sales * 0.05) as avg_commission +FROM employees +GROUP BY department; +``` + +| department | avg_commission +:--- | :--- +1 | 733.75 | +2 | 925.45 | + +### COUNT + +`COUNT` 函数接受 `*` 之类的参数或 `1` 之类的字面量。 +下表说明了 `COUNT` 函数各种形式的工作方式。 + +| 函数类型 | 描述 +`COUNT(field)` | 统计给定字段(或表达式)的值不为 null 的行数。 +`COUNT(*)` | 统计表中的总行数。 +`COUNT(1)`(与 `COUNT(*)` 相同) | 统计任意非 null 字面量。 + +例如,以下查询返回每年的销售次数: + +```sql +SELECT year(sale_date), count(sales) +FROM employees +GROUP BY year(sale_date); +``` + +| year(sale_date) | count(sales) +:--- | :--- +2020 | 1 +2021 | 2 +2022 | 3 + +## HAVING + +`WHERE` 和 `HAVING` 都用于过滤结果。`WHERE` 过滤在 `GROUP BY` 阶段之前执行,因此不能在 `WHERE` 子句中使用聚合函数。不过,可以用 `WHERE` 子句限制随后参与聚合的行。 + +`HAVING` 过滤在 `GROUP BY` 阶段之后执行,因此可以用 `HAVING` 子句限制结果中包含哪些分组。 + +### 带 GROUP BY 的 HAVING + +可以在 `HAVING` 条件中使用聚合表达式,或者使用在 `SELECT` 子句中为它们定义的别名。 + +以下查询在 `HAVING` 子句中使用聚合表达式,返回销售次数多于一次的每位员工的销售次数: + +```sql +SELECT employee_id, count(sales) +FROM employees +GROUP BY employee_id +HAVING count(sales) > 1; +``` + +| employee_id | count(sales) +:--- | :--- +1 | 2 | +6 | 2 + +`HAVING` 子句中的聚合不必与 `SELECT` 列表中的聚合相同。以下查询在 `HAVING` 子句中使用 `count` 函数,而在 `SELECT` 子句中使用 `sum` 函数,返回销售次数多于一次的每位员工的销售总额: + +```sql +SELECT employee_id, sum(sales) +FROM employees +GROUP BY employee_id +HAVING count(sales) > 1; +``` + +| employee_id | sum (sales) +:--- | :--- +1 | 40580 | +6 | 18120 + +作为对 SQL 标准的扩展,`GROUP BY` 子句中并不限于只使用标识符。以下查询在 `GROUP BY` 子句中使用了别名,与上一个查询等价: + +```sql +SELECT employee_id as id, sum(sales) +FROM employees +GROUP BY id +HAVING count(sales) > 1; +``` + +| id | sum (sales) +:--- | :--- +1 | 40580 | +6 | 18120 + +也可以在 `HAVING` 子句中使用聚合表达式的别名。以下查询返回销售额超过 $40,000 的各部门的销售总额: + +```sql +SELECT department, sum(sales) as total +FROM employees +GROUP BY department +HAVING total > 40000; +``` + +| department | total +:--- | :--- +1 | 58700 | + +如果某个标识符有歧义(例如,它既是 `SELECT` 中的别名,又是索引中的字段),则优先使用别名。在以下查询中,该标识符会被替换为 `SELECT` 子句中以它为别名的表达式: + +```sql +SELECT department, sum(sales) as sales +FROM employees +GROUP BY department +HAVING sales > 40000; +``` + +| department | sales +:--- | :--- +1 | 58700 | + +### 不带 GROUP BY 的 HAVING + +可以在没有 `GROUP BY` 子句的情况下使用 `HAVING` 子句。这时整个数据集被视为一个分组。如果 `department` 列中有不止一个值,以下查询将返回 `True`: + +```sql +SELECT 'True' as more_than_one_department FROM employees HAVING min(department) < max(department); +``` + +| more_than_one_department | +:--- | +True | + +如果员工表中的所有员工都属于同一个部门,结果将不包含任何行: + +| more_than_one_department +:--- | + | diff --git a/i18n/zh/search-plugins/sql/sql/basic.md b/i18n/zh/search-plugins/sql/sql/basic.md new file mode 100644 index 00000000..988dccce --- /dev/null +++ b/i18n/zh/search-plugins/sql/sql/basic.md @@ -0,0 +1,355 @@ +--- +title: 基本查询 +--- + +# 基本查询 + +使用 `SELECT` 子句,配合 `FROM`、`WHERE`、`GROUP BY`、`HAVING`、`ORDER BY` 和 `LIMIT` 来搜索和聚合数据。 + +在这些子句中,`SELECT` 和 `FROM` 是必需的,因为它们指定要检索哪些字段以及从哪些索引中检索。其他子句都是可选的,可根据需要使用。 + +### 语法 + +搜索和聚合数据的完整语法如下: + +```sql +SELECT [DISTINCT] (* | expression) [[AS] alias] [, ...] +FROM index_name +[WHERE predicates] +[GROUP BY expression [, ...] + [HAVING predicates]] +[ORDER BY expression [IS [NOT] NULL] [ASC | DESC] [, ...]] +[LIMIT [offset, ] size] +``` + +### 基础知识 + +除了 SQL 预定义的关键字之外,最基本的元素是字面量(literal)和标识符(identifier)。 +字面量是数值、字符串、日期或布尔常量。标识符是 OpenSearch 索引名称或字段名称。 +借助算术运算符和 SQL 函数,可以用字面量和标识符构建复杂的表达式。 + +规则 `expressionAtom`: + +![expressionAtom](/images/expressionAtom.png) + +表达式又可以通过逻辑运算符组合成谓词。在 `WHERE` 和 `HAVING` 子句中使用谓词,可以按特定条件过滤数据。 + +规则 `expression`: + +![expression](/images/expression.png) + +规则 `predicate`: + +![expression](/images/predicate.png) + +### 执行顺序 + +这些 SQL 子句的执行顺序与它们在语句中出现的顺序不同: + +```sql +FROM index + WHERE predicates + GROUP BY expressions + HAVING predicates + SELECT expressions + ORDER BY expressions + LIMIT size +``` + +## Select + +指定要检索的字段。 + +### 语法 {#syntax-1} + +规则 `selectElements`: + +![selectElements](/images/selectElements.png) + +规则 `selectElement`: + +![selectElements](/images/selectElement.png) + +*示例 1*: 使用 `*` 检索索引中的所有字段: + +```sql +SELECT * +FROM accounts +``` + +| account_number | firstname | gender | city | balance | employer | state | email | address | lastname | age +| :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- +| 1 | Amber | M | Brogan | 39225 | Pyrami | IL | amberduke@pyrami.com | 880 Holmes Lane | Duke | 32 +| 16 | Hattie | M | Dante | 5686 | Netagy | TN | hattiebond@netagy.com | 671 Bristol Street | Bond | 36 +| 13 | Nanette | F | Nogal | 32838 | Quility | VA | nanettebates@quility.com | 789 Madison Street | Bates | 28 +| 18 | Dale | M | Orick | 4180 | | MD | daleadams@boink.com | 467 Hutchinson Court | Adams | 33 + +*示例 2*: 使用字段名称只检索特定字段: + +```sql +SELECT firstname, lastname +FROM accounts +``` + +| firstname | lastname +| :--- | :--- +| Amber | Duke +| Hattie | Bond +| Nanette | Bates +| Dale | Adams + +*示例 3*: 使用字段别名代替字段名称。字段别名可以让字段名称更易读: + +```sql +SELECT account_number AS num +FROM accounts +``` + +| num +:--- +| 1 +| 6 +| 13 +| 18 + +*示例 4*: 使用 `DISTINCT` 子句只返回唯一的字段值。可以指定一个或多个字段名称: + +```sql +SELECT DISTINCT age +FROM accounts +``` + +| age +:--- +| 28 +| 32 +| 33 +| 36 + +## From + +指定要搜索的索引。 +可以在 `FROM` 子句中指定子查询。 + +### 语法 {#syntax-2} + +规则 `tableName`: + +![tableName](/images/tableName.png) + +*示例 1*: 使用索引别名跨索引查询。关于索引别名的信息,请参阅[索引别名](/im-plugin/index-alias)。 +在这个示例查询中,`acc` 是 `accounts` 索引的别名: + +```sql +SELECT account_number, accounts.age +FROM accounts +``` + +或者 + +```sql +SELECT account_number, acc.age +FROM accounts acc +``` + +| account_number | age +| :--- | :--- +| 1 | 32 +| 6 | 36 +| 13 | 28 +| 18 | 33 + +*示例 2*: 使用索引模式查询与特定模式匹配的索引: + +```sql +SELECT account_number +FROM account* +``` + +| account_number +:--- +| 1 +| 6 +| 13 +| 18 + +## Where + +指定过滤结果的条件。 + +| 运算符 | 行为 +:--- | :--- +`=` | 等于。 +`<>` | 不等于。 +`>` | 大于。 +`<` | 小于。 +`>=` | 大于或等于。 +`<=` | 小于或等于。 +`IN` | 指定多个 `OR` 运算符。 +`BETWEEN` | 类似于范围查询。关于范围查询的更多信息,请参阅 [Range 查询](/query-dsl/term/range)。 +`LIKE` | 用于全文搜索。关于全文查询的更多信息,请参阅[全文查询](/query-dsl/full-text/)。 +`IS NULL` | 检查字段值是否为 `NULL`。 +`IS NOT NULL` | 检查字段值是否为 `NOT NULL`。 + +将比较运算符(`=`、`<>`、`>`、`>=`、`<`、`<=`)与布尔运算符 `NOT`、`AND` 或 `OR` 组合,可以构建更复杂的表达式。 + +*示例 1*: 对数值、字符串或日期使用比较运算符: + +```sql +SELECT account_number +FROM accounts +WHERE account_number = 1 +``` + +| account_number +| :--- +| 1 + +*示例 2*: OpenSearch 支持灵活的 schema,因此同一索引中的文档可能具有不同的字段。使用 `IS NULL` 或 `IS NOT NULL` 可以只检索缺失或存在的字段。OpenSearch 不区分缺失的字段和显式设置为 `NULL` 的字段: + +```sql +SELECT account_number, employer +FROM accounts +WHERE employer IS NULL +``` + +| account_number | employer +| :--- | :--- +| 18 | + +*示例 3*: 删除满足 `WHERE` 子句中谓词条件的文档: + +```sql +DELETE FROM accounts +WHERE age > 30 +``` + +## Group By + +将具有相同字段值的文档分组到桶(bucket)中。 + +*示例 1*: 按字段分组: + +```sql +SELECT age +FROM accounts +GROUP BY age +``` + +| id | age +:--- | :--- +0 | 28 +1 | 32 +2 | 33 +3 | 36 + +*示例 2*: 按字段别名分组: + +```sql +SELECT account_number AS num +FROM accounts +GROUP BY num +``` + +| id | num +:--- | :--- +0 | 1 +1 | 6 +2 | 13 +3 | 18 + +*示例 4*: 在 `GROUP BY` 子句中使用标量函数: + +```sql +SELECT ABS(age) AS a +FROM accounts +GROUP BY ABS(age) +``` + +| id | a +:--- | :--- +0 | 28.0 +1 | 32.0 +2 | 33.0 +3 | 36.0 + +## Having + +使用 `HAVING` 子句,基于聚合函数(`COUNT`、`AVG`、`SUM`、`MIN` 和 `MAX`)在每个桶内进行聚合。 +`HAVING` 子句对 `GROUP BY` 子句的结果进行过滤: + +*示例 1*: + +```sql +SELECT age, MAX(balance) +FROM accounts +GROUP BY age HAVING MIN(balance) > 10000 +``` + +| id | age | MAX (balance) +:--- | :--- +0 | 28 | 32838 +1 | 32 | 39225 + +## Order By + +使用 `ORDER BY` 子句按所需顺序对结果排序。 + +*示例 1*: 使用 `ORDER BY` 按升序或降序排序。除了普通字段名称之外,还支持使用 `ordinal`、`alias` 或 `scalar` 函数: + +```sql +SELECT account_number +FROM accounts +ORDER BY account_number DESC +``` + +| account_number +| :--- +| 18 +| 13 +| 6 +| 1 + +*示例 2*: 指定缺失字段的文档排在结果的开头还是末尾。OpenSearch 的默认行为是把 null 值或缺失字段放在最后返回。要把它们排在非 null 值之前,请使用 `IS NOT NULL` 运算符: + +```sql +SELECT employer +FROM accounts +ORDER BY employer IS NOT NULL +``` + +| employer +| :--- +|| +| Netagy +| Pyrami +| Quility + +## Limit + +指定要检索的最大文档数。用于避免把大量数据读入内存。 + +*示例 1*: 如果只传入一个参数,它会映射到 OpenSearch 中的 `size` 参数,`from` 参数则设置为 0。 + +```sql +SELECT account_number +FROM accounts +ORDER BY account_number LIMIT 1 +``` + +| account_number +| :--- +| 1 + +*示例 2*: 如果传入两个参数,第一个参数映射到 OpenSearch 中的 `from` 参数,第二个映射到 `size` 参数。这种方式可用于小型索引的简单分页,但对大型索引效率不高。 +使用 `ORDER BY` 确保各页之间的顺序一致: + +```sql +SELECT account_number +FROM accounts +ORDER BY account_number LIMIT 1, 1 +``` + +| account_number +| :--- +| 6 diff --git a/i18n/zh/search-plugins/sql/sql/complex.md b/i18n/zh/search-plugins/sql/sql/complex.md new file mode 100644 index 00000000..ecd42883 --- /dev/null +++ b/i18n/zh/search-plugins/sql/sql/complex.md @@ -0,0 +1,417 @@ +--- +title: 复杂查询 +--- + +# 复杂查询 + +除了简单的 SFW(`SELECT-FROM-WHERE`)查询之外,SQL 插件还支持子查询、连接(join)、并集(union)和差集(minus)等复杂查询。这些查询会作用于多个 OpenSearch 索引。要了解这些查询在后台是如何执行的,请使用 `explain` 操作。 + +## 连接 + +OpenSearch SQL 支持内连接(inner join)、交叉连接(cross join)和左外连接(left outer join)。 + +### 限制 + +连接有以下限制: + +1. 只能连接两个索引。 +1. 必须为索引使用别名(例如 `people p`)。 +1. 在 ON 子句中只能使用 AND 条件。 +1. 在 WHERE 语句中,不要组合包含多个索引的条件树。例如,下面的语句可以正常工作: + + ``` + WHERE (a.type1 > 3 OR a.type1 < 0) AND (b.type2 > 4 OR b.type2 < -1) + ``` + + 而下面的语句不行: + + ``` + WHERE (a.type1 > 3 OR b.type2 < 0) AND (a.type1 > 4 OR b.type2 < -1) + ``` + +1. 不能对结果使用 GROUP BY 或 ORDER BY。 +1. 不支持带 OFFSET 的 LIMIT(例如 `LIMIT 25 OFFSET 25`)。 + +### 描述 + +`JOIN` 子句使用各索引共有的值,将一个或多个索引中的列组合起来。 + +### 语法 + +规则 `tableSource`: + +![tableSource](/images/tableSource.png) + +规则 `joinPart`: + +![joinPart](/images/joinPart.png) + +### 示例 1:内连接 + +内连接根据连接谓词组合两个索引的列,生成新的结果集。它遍历两个索引,比较每个文档,找出满足连接谓词的文档。可以选择在 `JOIN` 子句前加上 `INNER` 关键字。 + +连接谓词由 ON 子句指定。 + +SQL 查询: + +```sql +SELECT + a.account_number, a.firstname, a.lastname, + e.id, e.name +FROM accounts a +JOIN employees_nested e + ON a.account_number = e.id +``` + +Explain: + +`explain` 的输出比较复杂,因为一个 `JOIN` 子句关联了两个 OpenSearch DSL 查询,它们分别在不同的查询规划器框架中执行。可以通过查看 `Physical Plan` 和 `Logical Plan` 对象来理解它。 + +```json +{ + "Physical Plan" : { + "Project [ columns=[a.account_number, a.firstname, a.lastname, e.name, e.id] ]" : { + "Top [ count=200 ]" : { + "BlockHashJoin[ conditions=( a.account_number = e.id ), type=JOIN, blockSize=[FixedBlockSize with size=10000] ]" : { + "Scroll [ employees_nested as e, pageSize=10000 ]" : { + "request" : { + "size" : 200, + "from" : 0, + "_source" : { + "excludes" : [ ], + "includes" : [ + "id", + "name" + ] + } + } + }, + "Scroll [ accounts as a, pageSize=10000 ]" : { + "request" : { + "size" : 200, + "from" : 0, + "_source" : { + "excludes" : [ ], + "includes" : [ + "account_number", + "firstname", + "lastname" + ] + } + } + }, + "useTermsFilterOptimization" : false + } + } + } + }, + "description" : "Hash Join algorithm builds hash table based on result of first query, and then probes hash table to find matched rows for each row returned by second query", + "Logical Plan" : { + "Project [ columns=[a.account_number, a.firstname, a.lastname, e.name, e.id] ]" : { + "Top [ count=200 ]" : { + "Join [ conditions=( a.account_number = e.id ) type=JOIN ]" : { + "Group" : [ + { + "Project [ columns=[a.account_number, a.firstname, a.lastname] ]" : { + "TableScan" : { + "tableAlias" : "a", + "tableName" : "accounts" + } + } + }, + { + "Project [ columns=[e.name, e.id] ]" : { + "TableScan" : { + "tableAlias" : "e", + "tableName" : "employees_nested" + } + } + } + ] + } + } + } + } +} +``` + +结果集: + +| a.account_number | a.firstname | a.lastname | e.id | e.name +:--- | :--- | :--- | :--- | :--- +6 | Hattie | Bond | 6 | Jane Smith + +### 示例 2:交叉连接 + +交叉连接也称为笛卡尔连接(cartesian join),它将第一个索引中的每个文档与第二个索引中的每个文档组合起来。 +结果集是两个索引中文档的笛卡尔积。 +该操作类似于没有指定连接条件的 `ON` 子句的内连接。 + +::: danger 警告 +对两个大型甚至中型索引执行交叉连接是有风险的。它可能会触发断路器,为避免内存耗尽而终止查询。 +::: + +SQL 查询: + +```sql +SELECT + a.account_number, a.firstname, a.lastname, + e.id, e.name +FROM accounts a +JOIN employees_nested e +``` + +结果集: + +| a.account_number | a.firstname | a.lastname | e.id | e.name +:--- | :--- | :--- | :--- | :--- +1 | Amber | Duke | 3 | Bob Smith +1 | Amber | Duke | 4 | Susan Smith +1 | Amber | Duke | 6 | Jane Smith +6 | Hattie | Bond | 3 | Bob Smith +6 | Hattie | Bond | 4 | Susan Smith +6 | Hattie | Bond | 6 | Jane Smith +13 | Nanette | Bates | 3 | Bob Smith +13 | Nanette | Bates | 4 | Susan Smith +13 | Nanette | Bates | 6 | Jane Smith +18 | Dale | Adams | 3 | Bob Smith +18 | Dale | Adams | 4 | Susan Smith +18 | Dale | Adams | 6 | Jane Smith + +### 示例 3:左外连接 + +使用左外连接,可以在第一个索引中的行不满足连接谓词时仍保留这些行。关键字 `OUTER` 是可选的。 + +SQL 查询: + +```sql +SELECT + a.account_number, a.firstname, a.lastname, + e.id, e.name +FROM accounts a +LEFT JOIN employees_nested e + ON a.account_number = e.id +``` + +结果集: + +| a.account_number | a.firstname | a.lastname | e.id | e.name +:--- | :--- | :--- | :--- | :--- +1 | Amber | Duke | null | null +6 | Hattie | Bond | 6 | Jane Smith +13 | Nanette | Bates | null | null +18 | Dale | Adams | null | null + +## 子查询 + +子查询是在另一个语句中使用、并用括号括起来的完整 `SELECT` 语句。 +从 explain 输出中可以看到,有些子查询实际上会被转换为等价的连接查询来执行。 + +### 示例 1:表子查询 + +SQL 查询: + +```sql +SELECT a1.firstname, a1.lastname, a1.balance +FROM accounts a1 +WHERE a1.account_number IN ( + SELECT a2.account_number + FROM accounts a2 + WHERE a2.balance > 10000 +) +``` + +Explain: + +```json +{ + "Physical Plan" : { + "Project [ columns=[a1.balance, a1.firstname, a1.lastname] ]" : { + "Top [ count=200 ]" : { + "BlockHashJoin[ conditions=( a1.account_number = a2.account_number ), type=JOIN, blockSize=[FixedBlockSize with size=10000] ]" : { + "Scroll [ accounts as a2, pageSize=10000 ]" : { + "request" : { + "size" : 200, + "query" : { + "bool" : { + "filter" : [ + { + "bool" : { + "adjust_pure_negative" : true, + "must" : [ + { + "bool" : { + "adjust_pure_negative" : true, + "must" : [ + { + "bool" : { + "adjust_pure_negative" : true, + "must_not" : [ + { + "bool" : { + "adjust_pure_negative" : true, + "must_not" : [ + { + "exists" : { + "field" : "account_number", + "boost" : 1 + } + } + ], + "boost" : 1 + } + } + ], + "boost" : 1 + } + }, + { + "range" : { + "balance" : { + "include_lower" : false, + "include_upper" : true, + "from" : 10000, + "boost" : 1, + "to" : null + } + } + } + ], + "boost" : 1 + } + } + ], + "boost" : 1 + } + } + ], + "adjust_pure_negative" : true, + "boost" : 1 + } + }, + "from" : 0 + } + }, + "Scroll [ accounts as a1, pageSize=10000 ]" : { + "request" : { + "size" : 200, + "from" : 0, + "_source" : { + "excludes" : [ ], + "includes" : [ + "firstname", + "lastname", + "balance", + "account_number" + ] + } + } + }, + "useTermsFilterOptimization" : false + } + } + } + }, + "description" : "Hash Join algorithm builds hash table based on result of first query, and then probes hash table to find matched rows for each row returned by second query", + "Logical Plan" : { + "Project [ columns=[a1.balance, a1.firstname, a1.lastname] ]" : { + "Top [ count=200 ]" : { + "Join [ conditions=( a1.account_number = a2.account_number ) type=JOIN ]" : { + "Group" : [ + { + "Project [ columns=[a1.balance, a1.firstname, a1.lastname, a1.account_number] ]" : { + "TableScan" : { + "tableAlias" : "a1", + "tableName" : "accounts" + } + } + }, + { + "Project [ columns=[a2.account_number] ]" : { + "Filter [ conditions=[AND ( AND account_number ISN null, AND balance GT 10000 ) ] ]" : { + "TableScan" : { + "tableAlias" : "a2", + "tableName" : "accounts" + } + } + } + } + ] + } + } + } + } +} +``` + +结果集: + +| a1.firstname | a1.lastname | a1.balance +:--- | :--- | :--- +Amber | Duke | 39225 +Nanette | Bates | 32838 + +### 示例 2:From 子查询 + +SQL 查询: + +```sql +SELECT a.f, a.l, a.a +FROM ( + SELECT firstname AS f, lastname AS l, age AS a + FROM accounts + WHERE age > 30 +) AS a +``` + +Explain: + +```json +{ + "from" : 0, + "size" : 200, + "query" : { + "bool" : { + "filter" : [ + { + "bool" : { + "must" : [ + { + "range" : { + "age" : { + "from" : 30, + "to" : null, + "include_lower" : false, + "include_upper" : true, + "boost" : 1.0 + } + } + } + ], + "adjust_pure_negative" : true, + "boost" : 1.0 + } + } + ], + "adjust_pure_negative" : true, + "boost" : 1.0 + } + }, + "_source" : { + "includes" : [ + "firstname", + "lastname", + "age" + ], + "excludes" : [ ] + } +} +``` + +结果集: + +| f | l | a +:--- | :--- | :--- +Amber | Duke | 32 +Dale | Adams | 33 +Hattie | Bond | 36 diff --git a/i18n/zh/search-plugins/sql/sql/delete.md b/i18n/zh/search-plugins/sql/sql/delete.md new file mode 100644 index 00000000..b98110c9 --- /dev/null +++ b/i18n/zh/search-plugins/sql/sql/delete.md @@ -0,0 +1,87 @@ +--- +title: Delete +--- + +# Delete + +`DELETE` 语句删除满足 `WHERE` 子句中谓词条件的文档。 +如果不指定 `WHERE` 子句,将删除所有文档。 + +### 设置 + +`DELETE` 语句默认处于禁用状态。要在 SQL 中启用 `DELETE` 功能,需要发送以下请求来更新配置: + +```json +PUT _plugins/_query/settings +{ + "transient": { + "plugins.sql.delete.enabled": "true" + } +} +``` + +### 语法 + +规则 `singleDeleteStatement`: + +![singleDeleteStatement](/images/singleDeleteStatement.png) + +### 示例 + +SQL 查询: + +```sql +DELETE FROM accounts +WHERE age > 30 +``` + +Explain: + +```json +{ + "size" : 1000, + "query" : { + "bool" : { + "must" : [ + { + "range" : { + "age" : { + "from" : 30, + "to" : null, + "include_lower" : false, + "include_upper" : true, + "boost" : 1.0 + } + } + } + ], + "adjust_pure_negative" : true, + "boost" : 1.0 + } + }, + "_source" : false +} +``` + +结果集: + +```json +{ + "schema" : [ + { + "name" : "deleted_rows", + "type" : "long" + } + ], + "total" : 1, + "datarows" : [ + [ + 3 + ] + ], + "size" : 1, + "status" : 200 +} +``` + +`datarows` 字段显示已删除的文档数量。 diff --git a/i18n/zh/search-plugins/sql/sql/functions.md b/i18n/zh/search-plugins/sql/sql/functions.md new file mode 100644 index 00000000..ce8a7b74 --- /dev/null +++ b/i18n/zh/search-plugins/sql/sql/functions.md @@ -0,0 +1,221 @@ +--- +title: 函数 +--- + +# 函数 + +SQL 语言支持 SQL 插件的所有[通用函数](/search-plugins/sql/functions),包括[相关性搜索](/search-plugins/sql/full-text)函数,此外还引入了几个仅在 SQL 中可用的函数同义词。 +这些同义词由 `V1` 引擎提供。更多信息请参阅[限制](/search-plugins/sql/limitation)。 + +## Match 查询 + +`MATCHQUERY` 和 `MATCH_QUERY` 函数是 [`MATCH`](/search-plugins/sql/full-text#match) 相关性函数的同义词。它们不接受额外的参数,只是提供了另一种语法。 + +### 语法 + +要使用 `matchquery` 或 `match_query`,请传入搜索查询以及要搜索的字段名称: + +```sql +match_query(field_expression, query_expression[, option=]*) +matchquery(field_expression, query_expression[, option=]*) +field_expression = match_query(query_expression[, option=]*) +field_expression = matchquery(query_expression[, option=]*) +``` + +可以按任意顺序指定以下选项: + +- `analyzer` +- `boost` + +### 示例 + +可以使用 `MATCHQUERY` 代替 `MATCH`: + +```sql +SELECT account_number, address +FROM accounts +WHERE MATCHQUERY(address, 'Holmes') +``` + +也可以使用 `MATCH_QUERY` 代替 `MATCH`: + +```sql +SELECT account_number, address +FROM accounts +WHERE address = MATCH_QUERY('Holmes') +``` + +结果包含地址中含有“Holmes”的文档: + +| account_number | address +:--- | :--- +1 | 880 Holmes Lane + +## Multi-match + +[`MULTI_MATCH`](/search-plugins/sql/full-text#multi-match) 有三个同义词,语法略有不同。它们接受一个查询字符串和一个带权重的字段列表,还可以接受其他可选参数。 + +### 语法 {#syntax-1} + +```sql +multimatch('query'=query_expression[, 'fields'=field_expression][, option=]*) +multi_match('query'=query_expression[, 'fields'=field_expression][, option=]*) +multimatchquery('query'=query_expression[, 'fields'=field_expression][, option=]*) +``` + +`fields` 参数是可选的,可以包含单个字段或逗号分隔的字段列表(不允许包含空白字符)。每个字段的权重是可选的,在字段名称之后指定,用 `caret` 字符(`^`)分隔,中间不能有空白。 + +### 示例 {#example-1} + +以下查询展示了 multi-match 查询的 `fields` 参数分别使用单个字段和字段列表的情况: + +```sql +multi_match('fields' = "Tags^2,Title^3.4,Body,Comments^0.3", ...) +multi_match('fields' = "Title", ...) +``` + +可以按任意顺序指定以下选项: + +- `analyzer` +- `boost` +- `slop` +- `type` +- `tie_breaker` +- `operator` + +## Query string + +`QUERY` 函数是 [`QUERY_STRING`](/search-plugins/sql/full-text#query-string) 的同义词。 + +### 语法 {#syntax-2} + +```sql +query('query'=query_expression[, 'fields'=field_expression][, option=]*) +``` + +`fields` 参数是可选的,可以包含单个字段或逗号分隔的字段列表(不允许包含空白字符)。每个字段的权重是可选的,在字段名称之后指定,用 `caret` 字符(`^`)分隔,中间不能有空白。 + +### 示例 {#example-2} + +以下查询展示了 multi-match 查询的 `fields` 参数分别使用单个字段和字段列表的情况: + +```sql +query('fields' = "Tags^2,Title^3.4,Body,Comments^0.3", ...) +query('fields' = "Tags", ...) +``` + +可以按任意顺序指定以下选项: + +- `analyzer` +- `boost` +- `slop` +- `default_field` + +### 在 SQL 和 PPL 查询中使用 `query_string` 的示例: {#example-of-using-querystring-in-sql-and-ppl-queries} + +下面是一个使用 OpenSearch DSL 的 REST API 搜索请求示例。 + +```json +GET accounts/_search +{ + "query": { + "query_string": { + "query": "Lane Street", + "fields": [ "address" ], + } + } +} +``` + +上述请求等价于以下 `query` 函数: + +```sql +SELECT account_number, address +FROM accounts +WHERE query('address:Lane OR address:Street') +``` + +结果包含地址中含有“Lane”或“Street”的文档: + +| account_number | address +:--- | :--- +1 | 880 Holmes Lane +6 | 671 Bristol Street +13 | 789 Madison Street + +## Match phrase + +`MATCHPHRASEQUERY` 函数是 [`MATCH_PHRASE`](/search-plugins/sql/full-text#query-string) 的同义词。 + +### 语法 {#syntax-3} + +```sql +matchphrasequery(query_expression, field_expression[, option=]*) +``` + +可以按任意顺序指定以下选项: + +- `analyzer` +- `boost` +- `slop` + +## Score 查询 + +要在返回每个匹配文档的同时返回相关性评分(relevance score),请使用 `SCORE`、`SCOREQUERY` 或 `SCORE_QUERY` 函数。 + +### 语法 {#syntax-4} + +`SCORE` 函数需要两个参数。第一个参数是 [`MATCH_QUERY`](#match-query) 表达式。第二个参数是可选的浮点数,用于提升评分(默认值为 1.0): + +```sql +SCORE(match_query_expression, score) +SCOREQUERY(match_query_expression, score) +SCORE_QUERY(match_query_expression, score) +``` + +### 示例 {#example-3} + +以下示例使用 `SCORE` 函数提升文档的评分: + +```sql +SELECT account_number, address, _score +FROM accounts +WHERE SCORE(MATCH_QUERY(address, 'Lane'), 0.5) OR + SCORE(MATCH_QUERY(address, 'Street'), 100) +ORDER BY _score +``` + +结果包含匹配项及其对应的评分: + +| account_number | address | score +:--- | :--- | :--- +1 | 880 Holmes Lane | 0.5 +6 | 671 Bristol Street | 100 +13 | 789 Madison Street | 100 + +## Wildcard 查询 + +要按给定的通配符搜索文档,请使用 `WILDCARDQUERY` 或 `WILDCARD_QUERY` 函数。 + +### 语法 {#syntax-5} + +```sql +wildcardquery(field_expression, query_expression[, boost=]) +wildcard_query(field_expression, query_expression[, boost=]) +``` + +### 示例 {#example-4} + +以下示例使用通配符查询: + +```sql +SELECT account_number, address +FROM accounts +WHERE wildcard_query(address, '*Holmes*'); +``` + +结果包含与通配符表达式匹配的文档: + +| account_number | address +:--- | :--- +1 | 880 Holmes Lane diff --git a/i18n/zh/search-plugins/sql/sql/index.md b/i18n/zh/search-plugins/sql/sql/index.md new file mode 100644 index 00000000..ce31090f --- /dev/null +++ b/i18n/zh/search-plugins/sql/sql/index.md @@ -0,0 +1,65 @@ +--- +title: SQL +--- + +# SQL + +OpenSearch 中的 SQL 在传统关系型数据库概念与 OpenSearch 灵活的面向文档的数据存储之间架起了桥梁。借助这一集成,你可以利用已有的 SQL 知识来查询、分析 OpenSearch 中的数据,并从中获取洞察。 + +## SQL 与 OpenSearch 术语对照 + +SQL 核心概念与 OpenSearch 的对应关系如下: + +SQL | OpenSearch +:--- | :--- +表(Table) | 索引(Index) +行(Row) | 文档(Document) +列(Column) | 字段(Field) + +## REST API + +关于 SQL 插件完整的 REST API 参考,请参阅 [SQL/PPL API](/search-plugins/sql/sql-ppl-api)。 + +要在自己的应用程序中使用 SQL 插件,请向 `_plugins/_sql` 端点发送请求: + +```json +POST _plugins/_sql +{ + "query": "SELECT * FROM my-index LIMIT 50" +} +``` + +可以使用逗号分隔的列表查询多个索引: + +```json +POST _plugins/_sql +{ + "query": "SELECT * FROM my-index1,myindex2,myindex3 LIMIT 50" +} +``` + +可以使用通配符表达式指定索引模式: + +```json +POST _plugins/_sql +{ + "query": "SELECT * FROM my-index* LIMIT 50" +} +``` + +要在命令行中运行上述查询,请使用 [curl](https://curl.haxx.se/) 命令: + +```bash +curl -XPOST https://localhost:9200/_plugins/_sql -u 'admin:' -k -H 'Content-Type: application/json' -d '{"query": "SELECT * FROM my-index* LIMIT 50"}' +``` + +可以将[响应格式](/search-plugins/sql/response-formats)指定为 JDBC、标准 OpenSearch JSON、CSV 或原始格式(raw)。默认情况下,查询以 JDBC 格式返回数据。以下查询将格式设置为 JSON: + +```json +POST _plugins/_sql?format=json +{ + "query": "SELECT * FROM my-index LIMIT 50" +} +``` + +关于请求参数、设置、支持的操作和工具的更多信息,请参阅 [SQL](/search-plugins/sql/sql/) 下的相关主题。 diff --git a/i18n/zh/search-plugins/sql/sql/jdbc.md b/i18n/zh/search-plugins/sql/sql/jdbc.md new file mode 100644 index 00000000..8a6d7518 --- /dev/null +++ b/i18n/zh/search-plugins/sql/sql/jdbc.md @@ -0,0 +1,13 @@ +--- +title: JDBC 驱动程序 +--- + +# JDBC 驱动程序 + +Java 数据库连接(Java Database Connectivity,JDBC)驱动程序可以让你将 OpenSearch 与常用的商业智能(BI)应用程序集成。 + +关于下载和使用 JAR 文件的信息,请参阅 [GitHub 上的 SQL 仓库](https://github.com/opensearch-project/sql-jdbc)。 + +## 连接 Tableau + +要连接 Tableau,请按照 [GitHub 仓库](https://github.com/opensearch-project/sql-jdbc/blob/main/bi-connectors/TableauConnector/README.md)中的详细说明操作。 diff --git a/i18n/zh/search-plugins/sql/sql/metadata.md b/i18n/zh/search-plugins/sql/sql/metadata.md new file mode 100644 index 00000000..f69f8928 --- /dev/null +++ b/i18n/zh/search-plugins/sql/sql/metadata.md @@ -0,0 +1,65 @@ +--- +title: 元数据查询 +--- + +# 元数据查询 + +要查看索引的基本元数据,请使用 `SHOW` 和 `DESCRIBE` 命令。 + +### 语法 + +规则 `showStatement`: + +![showStatement](/images/showStatement.png) + +规则 `showFilter`: + +![showFilter](/images/showFilter.png) + +### 示例 1:查看索引的元数据 + +要查看与特定模式匹配的索引的元数据,请使用 `SHOW` 命令。 +使用通配符 `%` 匹配所有索引: + +```sql +SHOW TABLES LIKE % +``` + +| TABLE_CAT | TABLE_SCHEM | TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYPE_SCHEM | TYPE_NAME | SELF_REFERENCING_COL_NAME | REF_GENERATION +:--- | :--- +docker-cluster | null | accounts | BASE TABLE | null | null | null | null | null | null +docker-cluster | null | employees_nested | BASE TABLE | null | null | null | null | null | null + +### 示例 2:查看特定索引的元数据 + +要查看名称以 `acc` 为前缀的索引的元数据: + +```sql +SHOW TABLES LIKE acc% +``` + +| TABLE_CAT | TABLE_SCHEM | TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYPE_SCHEM | TYPE_NAME | SELF_REFERENCING_COL_NAME | REF_GENERATION +:--- | :--- +docker-cluster | null | accounts | BASE TABLE | null | null | null | null | null | null + +### 示例 3:查看字段的元数据 + +要查看与特定模式匹配的字段名称的元数据,请使用 `DESCRIBE` 命令: + +```sql +DESCRIBE TABLES LIKE accounts +``` + +| TABLE_CAT | TABLE_SCHEM | TABLE_NAME | COLUMN_NAME | DATA_TYPE | TYPE_NAME | COLUMN_SIZE | BUFFER_LENGTH | DECIMAL_DIGITS | NUM_PREC_RADIX | NULLABLE | REMARKS | COLUMN_DEF | SQL_DATA_TYPE | SQL_DATETIME_SUB | CHAR_OCTET_LENGTH | ORDINAL_POSITION | IS_NULLABLE | SCOPE_CATALOG | SCOPE_SCHEMA | SCOPE_TABLE | SOURCE_DATA_TYPE | IS_AUTOINCREMENT | IS_GENERATEDCOLUMN +:--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- +docker-cluster | null | accounts | account_number | null | long | null | null | null | 10 | 2 | null | null | null | null | null | 1 | | null | null | null | null | NO | +docker-cluster | null | accounts | firstname | null | text | null | null | null | 10 | 2 | null | null | null | null | null | 2 | | null | null | null | null | NO | +docker-cluster | null | accounts | address | null | text | null | null | null | 10 | 2 | null | null | null | null | null | 3 | | null | null | null | null | NO | +docker-cluster | null | accounts | balance | null | long | null | null | null | 10 | 2 | null | null | null | null | null | 4 | | null | null | null | null | NO | +docker-cluster | null | accounts | gender | null | text | null | null | null | 10 | 2 | null | null | null | null | null | 5 | | null | null | null | null | NO | +docker-cluster | null | accounts | city | null | text | null | null | null | 10 | 2 | null | null | null | null | null | 6 | | null | null | null | null | NO | +docker-cluster | null | accounts | employer | null | text | null | null | null | 10 | 2 | null | null | null | null | null | 7 | | null | null | null | null | NO | +docker-cluster | null | accounts | state | null | text | null | null | null | 10 | 2 | null | null | null | null | null | 8 | | null | null | null | null | NO | +docker-cluster | null | accounts | age | null | long | null | null | null | 10 | 2 | null | null | null | null | null | 9 | | null | null | null | null | NO | +docker-cluster | null | accounts | email | null | text | null | null | null | 10 | 2 | null | null | null | null | null | 10 | | null | null | null | null | NO | +docker-cluster | null | accounts | lastname | null | text | null | null | null | 10 | 2 | null | null | null | null | null | 11 | | null | null | null | null | NO | diff --git a/i18n/zh/search-plugins/sql/sql/odbc.md b/i18n/zh/search-plugins/sql/sql/odbc.md new file mode 100644 index 00000000..86161af7 --- /dev/null +++ b/i18n/zh/search-plugins/sql/sql/odbc.md @@ -0,0 +1,198 @@ +--- +title: ODBC 驱动程序 +--- + +# ODBC 驱动程序 + +开放式数据库连接(Open Database Connectivity,ODBC)驱动程序是一个适用于 Windows 和 macOS 的只读 ODBC 驱动程序,可以让 [Microsoft Excel](https://github.com/opensearch-project/sql-odbc/blob/main/docs/user/microsoft_excel_support.md)、[Power BI](https://github.com/opensearch-project/sql-odbc/blob/main/bi-connectors/PowerBIConnector/README.md) 等商业智能(BI)和数据可视化应用程序连接到 SQL 插件。 + +关于下载和使用该驱动程序的信息,请参阅 [GitHub 上的 SQL 仓库](https://github.com/opensearch-project/sql-odbc)。 + +## 规格 + +ODBC 驱动程序与 ODBC 3.51 版本兼容。 + +## 支持的操作系统版本 + +支持以下操作系统: + +操作系统 | 版本 +:--- | :--- +Windows | Windows 10, Windows 11 +macOS | Catalina 10.15.4, Mojave 10.14.6, Big Sur 11.6.7, Monterey 12.4 + +## 概念 + +术语 | 定义 +:--- | :--- +**DSN** | DSN(数据源名称,Data Source Name)用于在系统中存储驱动程序信息。把这些信息存储在系统中之后,驱动程序每次连接时就不需要再指定它们。 +**.tdc** 文件 | TDC 文件包含配置信息,Tableau 会将这些配置应用到与文件中定义的数据库供应商名称和驱动程序名称相匹配的所有连接上。借助此配置,可以对 ODBC 数据连接的某些部分进行微调,并开启或关闭数据源不支持的某些功能。 + +## 安装驱动程序 + +要安装驱动程序,请从[这里](https://opensearch.org/downloads.html)下载打包好的安装程序,或者从源代码构建。 + +### Windows + +1. 打开下载的 `OpenSearch SQL ODBC Driver--Windows.msi` 安装程序。 + + 该安装程序未经签名,会显示安全对话框。选择 **More info**,然后选择 **Run anyway**。 + +2. 选择 **Next** 继续安装。 + +3. 接受协议,然后选择 **Next**。 + +4. 安装程序附带了文档以及用于连接各种 BI 工具的实用资源文件(例如用于 Tableau 的 `.tdc` 文件)。可以选择保留或删除这些资源。选择 **Next**。 + +5. 选择 **Install**,然后选择 **Finish**。 + +默认 DSN 中设置了以下连接信息: + +``` +Host: localhost +Port: 9200 +Auth: NONE +``` + +要自定义 DSN,请使用 Windows 10 中预装的 **ODBC Data Source Administrator**。 + +### macOS + +在 macOS 上安装 ODBC 驱动程序之前,请先安装 iODBC Driver Manager。 + +1. 打开下载的 `OpenSearch SQL ODBC Driver--Darwin.pkg` 安装程序。 + + 该安装程序未经签名,会显示安全对话框。右键单击安装程序,然后选择 **Open**。 + +2. 多次选择 **Continue** 继续安装。 + +3. 选择 **Destination** 指定驱动程序文件的安装位置。 + +4. 安装程序附带了文档以及用于连接各种 BI 工具的实用资源文件(例如用于 Tableau 的 `.tdc` 文件)。可以选择保留或删除这些资源。选择 **Continue**。 + +5. 选择 **Install**,然后选择 **Close**。 + +目前,安装过程不会设置 DSN,需要手动配置。首先,打开 `iODBC Administrator`: + +``` +sudo /Applications/iODBC/iODBC\ Administrator64.app/Contents/MacOS/iODBC\ Administrator64 +``` + +该命令会授予应用程序保存驱动程序和 DSN 配置的权限。 + +1. 选择 **ODBC Drivers** 选项卡。 +2. 选择 **Add a Driver**,并填写以下信息: + - **Description of the Driver**:输入用于 ODBC 连接的驱动程序名称(例如 OpenSearch SQL ODBC Driver)。 + - **Driver File Name**:输入驱动程序文件的路径(默认值:`/bin/libopensearchsqlodbc.dylib`)。 + - **Setup File Name**:输入安装文件的路径(默认值:`/bin/libopensearchsqlodbc.dylib`)。 + +3. 选择用户驱动程序。 +4. 选择 **OK** 保存选项。 +5. 选择 **User DSN** 选项卡。 +6. 选择 **Add**。 +7. 选择上面添加的驱动程序。 +8. 在 **Data Source Name (DSN)** 中,输入用于存储连接选项的 DSN 名称(例如 OpenSearch SQL ODBC DSN)。 +9. 在 **Comment** 中,可以添加一条备注(可选)。 +10. 使用 `+` 按钮添加键值对。对于默认的本地 OpenSearch 安装,建议使用以下选项: + - **Host**:`localhost` - OpenSearch 服务器端点 + - **Port**:`9200` - 服务器端口 + - **Auth**:`NONE` - 身份验证模式 + - **Username**:`(blank)` - 用于 BASIC 身份验证的用户名 + - **Password**:`(blank)`- 用于 BASIC 身份验证的密码 + - **ResponseTimeout**:`10` - 等待服务器响应的秒数 + - **UseSSL**:`0` - 连接时不使用 SSL + +11. 选择 **OK** 保存 DSN 配置。 +12. 选择 **OK** 退出 iODBC Administrator。 + +## 自定义 ODBC 驱动程序 + +驱动程序以库文件的形式提供:Windows 上为 `opensearchsqlodbc.dll`,macOS 上为 `libopensearchsqlodbc.dylib`。 + +如果与兼容 ODBC 的 BI 工具一起使用,请参阅该 BI 工具的文档来配置新的 ODBC 驱动程序。 +通常只需让 BI 工具知道驱动程序库文件的位置,然后用它建立数据库(即 OpenSearch)连接即可。 + +### 连接字符串和其他设置 + +ODBC 驱动程序使用 ODBC 连接字符串。 +连接字符串是以分号分隔的字符串,用于指定连接时可以使用的一组选项。 +通常,连接字符串会采用以下两种方式之一: + - 指定一个包含预先配置好的选项集的数据源名称(DSN)(`DSN=xxx;User=xxx;Password=xxx;`)。 + - 或者,直接在字符串中显式配置选项(`Host=xxx;Port=xxx;LogLevel=ES_DEBUG;...`)。 + +可以使用 DSN 或连接字符串配置以下驱动程序选项: + +::: info 注意 +所有选项名称都不区分大小写。 +::: + +#### 基本选项 + +选项 | 描述 | 类型 | 默认值 +:--- | :--- +`DSN` | 配置连接时使用的数据源名称。 | `string` | - +`Host / Server` | 目标集群的主机名或 IP 地址。 | `string` | - +`Port` | OpenSearch 集群 REST 接口监听的端口号。 | `string` | - + +#### 身份验证选项 + +选项 | 描述 | 类型 | 默认值 +:--- | :--- +`Auth` | 要使用的身份验证机制。 | `BASIC`(基本 HTTP 身份验证)、`AWS_SIGV4`(AWS 身份验证)或 `NONE` | `NONE` +`User / UID` | [`Auth=BASIC`] 连接使用的用户名。 | `string` | - +`Password / PWD` | [`Auth=BASIC`] 连接使用的密码。 | `string` | - +`Region` | [`Auth=AWS_SIGV4`] 用于签名请求的区域。 | `AWS region (for example, us-west-1)` | - + +#### 高级选项 + +选项 | 描述 | 类型 | 默认值 +:--- | :--- +`UseSSL` | 是否通过 SSL/TLS 建立连接。 | `boolean (0 or 1)` | `false (0)` +`HostnameVerification` | 指示是否应对 SSL/TLS 连接执行证书主机名验证。 | `boolean`(0 或 1) | `true (1)` +`ResponseTimeout` | 等待主机响应的最长时间,以秒为单位。 | `integer` | `10` + +#### 日志选项 + +选项 | 描述 | 类型 | 默认值 +:--- | :--- +`LogLevel` | 驱动程序日志的严重级别。 | `LOG_OFF`、`LOG_FATAL`、`LOG_ERROR`、`LOG_INFO`、`LOG_DEBUG`、`LOG_TRACE` 或 `LOG_ALL` | `LOG_WARNING` +`LogOutput` | 驱动程序日志的存储位置。 | `string` | `WIN: C:\`, `MAC: /tmp` + +::: info 注意 +更改日志选项需要管理员权限。 +::: + +## 连接 Tableau + +前提条件: + +- 确保已设置好 DSN。 +- 确保 OpenSearch 正在 DSN 中配置的 *host* 和 *port* 上运行。 +- 确保在 macOS 和 Windows 上都已将 `.tdc` 复制到 `/Documents/My Tableau Repository/Datasources`。 + +1. 启动 Tableau。在 **Connect** 部分下,转到 **To a Server**,然后选择 **Other Databases (ODBC)**。 + +2. 在 **DSN drop-down** 中,选择在前面步骤中设置的 OpenSearch DSN。之前添加的选项会自动填入 **Connection Attributes** 中。 + +3. 选择 **Sign In**。几秒钟后,Tableau 会连接到 OpenSearch 服务器。连接成功后,会跳转到 **Datasource** 窗口。**Database** 中会自动填入 OpenSearch 集群的名称。 +要列出所有索引,请单击 **Table** 下方的搜索图标。 + +4. 将表拖到连接区域,开始试用数据。选择 **Update Now** 或 **Automatically Update** 来填充表数据。 + +更详细的说明请参阅 [GitHub 仓库](https://github.com/opensearch-project/sql/blob/1.x/sql-odbc/docs/user/tableau_support.md)。 + +### 故障排除 + +**问题** + +无法连接到服务器。 + +**解决方法** + +这很可能是因为 OpenSearch 服务器没有在 DSN 中配置的 **host** 和 **post** 上运行。 +请确认 **host** 和 **post** 正确无误,并且 OpenSearch 服务器正在运行且已安装 OpenSearch SQL 插件。 +另外,还要确保随安装程序一起下载的 `.tdc` 已正确复制到 `/Documents/My Tableau Repository/Datasources` 目录。 + +## 连接 Microsoft Power BI + +请按照 GitHub 仓库中发布的[安装说明](https://github.com/opensearch-project/sql-odbc/tree/main/bi-connectors/PowerBIConnector/README.md)和[配置说明](https://github.com/opensearch-project/sql-odbc/blob/main/bi-connectors/PowerBIConnector/power_bi_support.md)进行操作。 diff --git a/i18n/zh/search-plugins/sql/sql/partiql.md b/i18n/zh/search-plugins/sql/sql/partiql.md new file mode 100644 index 00000000..88b0569f --- /dev/null +++ b/i18n/zh/search-plugins/sql/sql/partiql.md @@ -0,0 +1,212 @@ +--- +title: JSON 支持 +--- + +# JSON 支持 + +SQL 插件遵循 [PartiQL](https://partiql.org/) 规范来支持 JSON。PartiQL 是一种与 SQL 兼容的查询语言,可以查询任意数据格式中的半结构化数据和嵌套数据。SQL 插件仅支持 PartiQL 规范的一个子集。 + +## 查询嵌套集合 + +PartiQL 对 SQL 进行了扩展,使你可以查询并展开(unnest)嵌套集合。在 OpenSearch 中,这对于查询包含嵌套对象或嵌套字段的 JSON 索引非常有用。 + +要跟着示例操作,请先使用 `bulk` 操作索引一些示例数据: + +```json +POST employees_nested/_bulk?refresh +{"index":{"_id":"1"}} +{"id":3,"name":"Bob Smith","title":null,"projects":[{"name":"SQL Spectrum querying","started_year":1990},{"name":"SQL security","started_year":1999},{"name":"OpenSearch security","started_year":2015}]} +{"index":{"_id":"2"}} +{"id":4,"name":"Susan Smith","title":"Dev Mgr","projects":[]} +{"index":{"_id":"3"}} +{"id":6,"name":"Jane Smith","title":"Software Eng 2","projects":[{"name":"SQL security","started_year":1998},{"name":"Hello security","started_year":2015,"address":[{"city":"Dallas","state":"TX"}]}]} +``` + +### 示例 1:展开嵌套集合 + +此示例查找字段值(`name`)满足谓词条件(包含 `security`)的嵌套文档(`projects`)。由于每个父文档可以有多个嵌套文档,匹配的嵌套文档会被展平。换句话说,最终结果是父文档与嵌套文档之间的笛卡尔积。 + +```sql +SELECT e.name AS employeeName, + p.name AS projectName +FROM employees_nested AS e, + e.projects AS p +WHERE p.name LIKE '%security%' +``` + +Explain: + +```json +{ + "from" : 0, + "size" : 200, + "query" : { + "bool" : { + "filter" : [ + { + "bool" : { + "must" : [ + { + "nested" : { + "query" : { + "wildcard" : { + "projects.name" : { + "wildcard" : "*security*", + "boost" : 1.0 + } + } + }, + "path" : "projects", + "ignore_unmapped" : false, + "score_mode" : "none", + "boost" : 1.0, + "inner_hits" : { + "ignore_unmapped" : false, + "from" : 0, + "size" : 3, + "version" : false, + "seq_no_primary_term" : false, + "explain" : false, + "track_scores" : false, + "_source" : { + "includes" : [ + "projects.name" + ], + "excludes" : [ ] + } + } + } + } + ], + "adjust_pure_negative" : true, + "boost" : 1.0 + } + } + ], + "adjust_pure_negative" : true, + "boost" : 1.0 + } + }, + "_source" : { + "includes" : [ + "name" + ], + "excludes" : [ ] + } +} +``` + +结果集: + +| employeeName | projectName +:--- | :--- +Bob Smith | OpenSearch Security +Bob Smith | SQL security +Jane Smith | Hello security +Jane Smith | SQL security + +### 示例 2:在存在性子查询中展开 + +在子查询中展开嵌套集合,检查其是否满足条件: + +```sql +SELECT e.name AS employeeName +FROM employees_nested AS e +WHERE EXISTS ( + SELECT * + FROM e.projects AS p + WHERE p.name LIKE '%security%' +) +``` + +Explain: + +```json +{ + "from" : 0, + "size" : 200, + "query" : { + "bool" : { + "filter" : [ + { + "bool" : { + "must" : [ + { + "nested" : { + "query" : { + "bool" : { + "must" : [ + { + "bool" : { + "must" : [ + { + "bool" : { + "must_not" : [ + { + "bool" : { + "must_not" : [ + { + "exists" : { + "field" : "projects", + "boost" : 1.0 + } + } + ], + "adjust_pure_negative" : true, + "boost" : 1.0 + } + } + ], + "adjust_pure_negative" : true, + "boost" : 1.0 + } + }, + { + "wildcard" : { + "projects.name" : { + "wildcard" : "*security*", + "boost" : 1.0 + } + } + } + ], + "adjust_pure_negative" : true, + "boost" : 1.0 + } + } + ], + "adjust_pure_negative" : true, + "boost" : 1.0 + } + }, + "path" : "projects", + "ignore_unmapped" : false, + "score_mode" : "none", + "boost" : 1.0 + } + } + ], + "adjust_pure_negative" : true, + "boost" : 1.0 + } + } + ], + "adjust_pure_negative" : true, + "boost" : 1.0 + } + }, + "_source" : { + "includes" : [ + "name" + ], + "excludes" : [ ] + } +} +``` + +结果集: + +| employeeName | +:--- | :--- +Bob Smith | +Jane Smith | diff --git a/i18n/zh/search-plugins/sql/troubleshoot.md b/i18n/zh/search-plugins/sql/troubleshoot.md new file mode 100644 index 00000000..973f76e9 --- /dev/null +++ b/i18n/zh/search-plugins/sql/troubleshoot.md @@ -0,0 +1,53 @@ +--- +title: 故障排除 +--- + +# 故障排除 + +SQL 插件是无状态的,因此故障排除主要集中在某个查询为什么会失败。 + +最常见的错误是令人头疼的空指针异常(null pointer exception),它可能在解析出错或使用了错误的 HTTP 方法(该用 POST 却用了 GET,或者反过来)时出现。使用 POST 方法并通过 HTTP 请求体发送查询,得到的结果最为一致: + +```json +POST _plugins/_sql +{ + "query": "SELECT * FROM my-index WHERE ['name.firstname']='saanvi' LIMIT 5" +} +``` + +如果某个查询的行为不符合预期,可以使用 `_explain` API 查看转换后的查询,然后据此排查问题。对于大多数操作,`_explain` 返回 OpenSearch Query DSL。对于 `UNION`、`MINUS` 和 `JOIN`,它返回的内容更接近 SQL 执行计划。 + +#### 示例请求 + +```json +POST _plugins/_sql/_explain +{ + "query": "SELECT * FROM my-index LIMIT 50" +} +``` + +#### 示例响应 + +```json +{ + "from": 0, + "size": 50 +} +``` + +## 索引映射验证异常 + +如果看到以下验证异常,请确保查询中的索引不是索引模式(index pattern),并且没有多个类型: + +```json +{ + "error": { + "reason": "There was internal problem at backend", + "details": "When using multiple indices, the mappings must be identical.", + "type": "VerificationException" + }, + "status": 503 +} +``` + +如果这些步骤都不起作用,请在[这里](https://github.com/opensearch-project/sql/issues)提交 GitHub issue。